/*
 * wificap — the 1.47" screen.
 *
 * This is the survey scanner's screen, kept deliberately: the big channel
 * readout, the busy bar, the dwell indicator and the per-channel heat strip
 * all mean the same things here. Two changes:
 *
 *   - the plan/sweep counters moved onto the title line, freeing a row
 *   - the bottom row is a handshake log line, which is the one event in this
 *     demo that the room is actually waiting for
 *
 * The handshake line latches. It is not a transient toast, because the whole
 * point is that someone can look over at the board a minute later and still
 * see that it caught something.
 *
 * SPDX-License-Identifier: MIT
 */

#include <stdio.h>
#include <string.h>

#include "esp_heap_caps.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "bsp/esp-bsp.h"
#include "lvgl.h"

#include "wcap.h"

static const char *TAG = "wcap.ui";

#if LV_FONT_MONTSERRAT_48
#define FONT_HUGE (&lv_font_montserrat_48)
#elif LV_FONT_MONTSERRAT_28
#define FONT_HUGE (&lv_font_montserrat_28)
#else
#define FONT_HUGE (&lv_font_montserrat_14)
#endif

#if LV_FONT_MONTSERRAT_20
#define FONT_MED (&lv_font_montserrat_20)
#else
#define FONT_MED (&lv_font_montserrat_14)
#endif

#define FONT_SMALL (&lv_font_montserrat_14)

#define COL_BG      0x000000
#define COL_DIM     0x5a5a5a
#define COL_TEXT    0xd8d8d8
#define COL_2G      0x3fa9f5
#define COL_5G      0x3fd97f
#define COL_WARN    0xf5a623
#define COL_BAD     0xe5484d
#define COL_HIT     0xffd166   /* the handshake line */
#define COL_CELL_0  0x1a1a1a
#define COL_UNAVAIL 0x3a1416

/* Heat strip geometry. Two pixels shorter than the survey scanner's, which is
 * what buys the row the handshake line sits on. */
#define CELL_W   9
#define CELL_GAP 2
#define CELL_H   16
#define CELL_Y   116
#define CELL_X0  7

static lv_obj_t *lbl_title, *lbl_up, *lbl_band, *lbl_ch;
static lv_obj_t *bar_dwell, *bar_busy, *lbl_busy;
static lv_obj_t *lbl_counts, *lbl_state, *lbl_hs;
static lv_obj_t *cells[WCAP_N_CHANNELS];

static uint32_t s_prev_hits[WCAP_N_CHANNELS];

/* ------------------------------------------------------------------ */

static lv_obj_t *mklabel(lv_obj_t *par, const lv_font_t *f, uint32_t colour,
                         lv_align_t align, int x, int y)
{
    lv_obj_t *l = lv_label_create(par);
    lv_obj_set_style_text_font(l, f, 0);
    lv_obj_set_style_text_color(l, lv_color_hex(colour), 0);
    lv_obj_align(l, align, x, y);
    lv_label_set_text(l, "");
    return l;
}

static lv_obj_t *mkbar(lv_obj_t *par, int x, int y, int w, int h, uint32_t colour)
{
    lv_obj_t *b = lv_bar_create(par);
    lv_obj_set_size(b, w, h);
    lv_obj_set_pos(b, x, y);
    lv_bar_set_range(b, 0, 100);
    lv_bar_set_value(b, 0, LV_ANIM_OFF);
    lv_obj_set_style_bg_color(b, lv_color_hex(0x1a1a1a), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(b, LV_OPA_COVER, LV_PART_MAIN);
    lv_obj_set_style_radius(b, 2, LV_PART_MAIN);
    lv_obj_set_style_bg_color(b, lv_color_hex(colour), LV_PART_INDICATOR);
    lv_obj_set_style_radius(b, 2, LV_PART_INDICATOR);
    return b;
}

esp_err_t wcap_ui_init(void)
{
    lv_display_t *disp = bsp_display_start();
    if (!disp) {
        ESP_LOGE(TAG, "bsp_display_start failed");
        return ESP_FAIL;
    }
    bsp_display_rotate(disp, LV_DISPLAY_ROTATION_90);
    ESP_ERROR_CHECK(bsp_display_brightness_set(CONFIG_WCAP_BRIGHTNESS));

    if (!bsp_display_lock(0)) return ESP_FAIL;

    lv_obj_t *scr = lv_screen_active();
    lv_obj_set_style_bg_color(scr, lv_color_hex(COL_BG), 0);
    lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0);
    lv_obj_remove_flag(scr, LV_OBJ_FLAG_SCROLLABLE);

    lbl_title = mklabel(scr, FONT_SMALL, COL_DIM, LV_ALIGN_TOP_LEFT, 6, 2);
    lbl_up    = mklabel(scr, FONT_SMALL, COL_DIM, LV_ALIGN_TOP_RIGHT, -6, 2);

    lbl_band = mklabel(scr, FONT_SMALL, COL_2G, LV_ALIGN_TOP_LEFT, 8, 26);
    lbl_ch   = mklabel(scr, FONT_HUGE, COL_TEXT, LV_ALIGN_TOP_LEFT, 6, 40);

    lbl_counts = mklabel(scr, FONT_SMALL, COL_TEXT, LV_ALIGN_TOP_RIGHT, -6, 24);
    lv_obj_set_style_text_align(lbl_counts, LV_TEXT_ALIGN_RIGHT, 0);

    lbl_busy = mklabel(scr, FONT_SMALL, COL_DIM, LV_ALIGN_TOP_LEFT, 6, 94);
    bar_busy = mkbar(scr, 60, 98, 254, 9, COL_5G);

    bar_dwell = mkbar(scr, 6, 110, 308, 4, COL_DIM);

    for (int i = 0; i < WCAP_N_CHANNELS; i++) {
        lv_obj_t *c = lv_obj_create(scr);
        lv_obj_remove_style_all(c);
        lv_obj_set_size(c, CELL_W, CELL_H);
        lv_obj_set_pos(c, CELL_X0 + i * (CELL_W + CELL_GAP), CELL_Y);
        lv_obj_set_style_bg_color(c, lv_color_hex(COL_CELL_0), 0);
        lv_obj_set_style_bg_opa(c, LV_OPA_COVER, 0);
        lv_obj_set_style_radius(c, 1, 0);
        cells[i] = c;
    }

    lbl_state = mklabel(scr, FONT_SMALL, COL_TEXT, LV_ALIGN_TOP_LEFT, 6, 135);
    lbl_hs    = mklabel(scr, FONT_SMALL, COL_HIT, LV_ALIGN_TOP_LEFT, 6, 152);

    bsp_display_unlock();
    ESP_LOGI(TAG, "ui up");
    return ESP_OK;
}

/* ------------------------------------------------------------------ */

static int busy_pct(uint32_t fps)
{
    if (fps == 0) return 0;
    if (fps >= 2000) return 100;
    int pct = 0;
    uint32_t v = fps;
    while (v > 0 && pct < 100) { v >>= 1; pct += 9; }
    return pct > 100 ? 100 : pct;
}

static uint32_t heat_colour(uint32_t delta, uint32_t peak)
{
    if (peak == 0 || delta == 0) return COL_CELL_0;
    uint32_t q = (delta * 4) / peak;
    switch (q) {
    case 0:  return 0x1f3a2a;
    case 1:  return 0x256b45;
    case 2:  return 0x3fd97f;
    case 3:  return 0xd9d13f;
    default: return 0xe5484d;
    }
}

void wcap_ui_task(void *arg)
{
    (void)arg;

    char buf[128];
    uint32_t stalls = 0;

    for (;;) {
        wcap_status_t st;
        wcap_status_get(&st);

        uint32_t delta[WCAP_N_CHANNELS];
        uint32_t peak = 1;
        for (int i = 0; i < WCAP_N_CHANNELS; i++) {
            delta[i] = st.hits_per_channel[i] - s_prev_hits[i];
            if (delta[i] > peak) peak = delta[i];
        }

        if (bsp_display_lock(50)) {
            /* Title line now carries the plan counters too. */
            snprintf(buf, sizeof(buf), "WIFICAP  plan %u/%u  sw %lu",
                     st.n_available, (unsigned)WCAP_N_CHANNELS,
                     (unsigned long)st.sweeps);
            lv_label_set_text(lbl_title, buf);

            uint32_t secs = wcap_tick_ms() / 1000;
            snprintf(buf, sizeof(buf), "%02lu:%02lu:%02lu  %luk",
                     (unsigned long)(secs / 3600),
                     (unsigned long)((secs / 60) % 60),
                     (unsigned long)(secs % 60),
                     (unsigned long)(esp_get_free_heap_size() / 1024));
            lv_label_set_text(lbl_up, buf);

            const bool g5 = st.is_5g;
            lv_label_set_text(lbl_band, g5 ? "5 GHz" : "2.4 GHz");
            lv_obj_set_style_text_color(lbl_band,
                                        lv_color_hex(g5 ? COL_5G : COL_2G), 0);
            snprintf(buf, sizeof(buf), "%u", st.channel);
            lv_label_set_text(lbl_ch, buf);
            lv_obj_set_style_text_color(lbl_ch,
                                        lv_color_hex(g5 ? COL_5G : COL_2G), 0);

            /*
             * Counters. `eapol` is the one to watch during a demo: it moves
             * before the handshake line appears, which is how you can tell
             * the board is seeing key frames but has not yet got a usable
             * pair.
             */
            snprintf(buf, sizeof(buf),
                     "ap %u\neapol %lu\nwrote %lu\ndrop %lu",
                     st.n_aps,
                     (unsigned long)st.eapol,
                     (unsigned long)st.written,
                     (unsigned long)st.dropped_ring);
            lv_label_set_text(lbl_counts, buf);
            lv_obj_set_style_text_color(
                lbl_counts, lv_color_hex(st.dropped_ring ? COL_WARN : COL_TEXT), 0);

            snprintf(buf, sizeof(buf), "%lu f/s", (unsigned long)st.fps);
            lv_label_set_text(lbl_busy, buf);
            int bp = busy_pct(st.fps);
            lv_bar_set_value(bar_busy, bp, LV_ANIM_OFF);
            lv_obj_set_style_bg_color(
                bar_busy,
                lv_color_hex(bp > 80 ? COL_BAD : bp > 50 ? COL_WARN : COL_5G),
                LV_PART_INDICATOR);

            int dp = st.dwell_ms ? (int)((st.dwell_elapsed_ms * 100) / st.dwell_ms) : 0;
            lv_bar_set_value(bar_dwell, dp > 100 ? 100 : dp, LV_ANIM_OFF);
            lv_obj_set_style_bg_color(
                bar_dwell,
                lv_color_hex(st.mode == WCAP_MODE_PARKED ? COL_HIT : COL_DIM),
                LV_PART_INDICATOR);

            for (int i = 0; i < WCAP_N_CHANNELS; i++) {
                uint32_t c;
                if (!st.available[i]) {
                    c = COL_UNAVAIL;
                } else if (wcap_plan[i] == st.channel) {
                    c = 0xffffff;
                } else {
                    c = heat_colour(delta[i], peak);
                }
                lv_obj_set_style_bg_color(cells[i], lv_color_hex(c), 0);
            }

            /*
             * State line: mode, recording, target -- unless the radio is
             * transmitting, in which case that is the only thing this line
             * says. A device that can transmit should never be quietly doing
             * it while the screen shows a plausible passive status.
             */
            if (st.active) {
                lv_label_set_text(lbl_state, "** ACTIVE - TRANSMITTING **");
                lv_obj_set_style_text_color(lbl_state, lv_color_hex(COL_BAD), 0);
                lv_label_set_text(lbl_hs, st.banner);
                lv_obj_set_style_text_color(lbl_hs, lv_color_hex(COL_BAD), 0);
                bsp_display_unlock();
                memcpy(s_prev_hits, st.hits_per_channel, sizeof(s_prev_hits));
                vTaskDelay(pdMS_TO_TICKS(CONFIG_WCAP_UI_PERIOD_MS));
                continue;
            }

            const char *mode = (st.mode == WCAP_MODE_PARKED) ? "PARK" : "SURVEY";
            const char *rec = st.rec == WCAP_REC_OFF ? "off"
                            : st.rec == WCAP_REC_HANDSHAKE ? "hs" : "all";
            if (st.have_target) {
                snprintf(buf, sizeof(buf), "%s rec:%s %02x%02x%02x %s",
                         mode, rec, st.target[3], st.target[4], st.target[5],
                         st.target_ssid[0] ? st.target_ssid : "?");
            } else {
                snprintf(buf, sizeof(buf), "%s rec:%s  %s",
                         mode, rec, st.sd_ok ? "sd ok" : "no sd");
            }
            lv_label_set_text(lbl_state, buf);
            lv_obj_set_style_text_color(
                lbl_state,
                lv_color_hex(st.rec != WCAP_REC_OFF ? COL_5G : COL_DIM), 0);

            /*
             * The handshake line. Latched, so it stays after the event.
             */
            lv_label_set_text(lbl_hs, st.banner);
            lv_obj_set_style_text_color(
                lbl_hs,
                lv_color_hex(st.any_crackable ? COL_HIT : COL_DIM), 0);

            bsp_display_unlock();

            memcpy(s_prev_hits, st.hits_per_channel, sizeof(s_prev_hits));
            stalls = 0;
        } else {
            /* A frozen screen showing a plausible channel is indistinguishable
             * from a working one, and it is otherwise completely silent. */
            if (++stalls == 25) {
                ESP_LOGW(TAG, "display lock missed %lu times in a row; "
                              "the screen is stale", (unsigned long)stalls);
            }
        }

        vTaskDelay(pdMS_TO_TICKS(CONFIG_WCAP_UI_PERIOD_MS));
    }
}
