#include <lgfx.h>
#include <lvgl.h>

#include "esp_vfs.h"
#include "esp_vfs_fat.h"
#include "esp_err.h"
#include "esp_log.h"

#include "image.h"

#define screenWidth (480)
#define screenHeight (320)

const unsigned int lvBufferSize = screenWidth * screenHeight / 10 * (LV_COLOR_DEPTH / 8);
uint8_t lvBuffer1[lvBufferSize];
uint8_t lvBuffer2[lvBufferSize];

static const char *TAG = "main";
const char *base_path = "/storage";

LGFX tft;

void setup_tft(void)
{
    tft.begin();
    tft.setRotation(1);
    tft.setBrightness(255);
}

void flush(lv_display_t *display, const lv_area_t *area, unsigned char *data)
{
    uint32_t w = lv_area_get_width(area);
    uint32_t h = lv_area_get_height(area);
    lv_draw_sw_rgb565_swap(data, w * h);
    tft.pushImageDMA(area->x1, area->y1, w, h, (uint16_t *)data);
    lv_display_flush_ready(display);
}

void my_touch_read(lv_indev_t *indev_driver, lv_indev_data_t *data)
{
    uint16_t touchX, touchY;
    bool touched = tft.getTouch(&touchX, &touchY);
    if (!touched)
    {
        data->state = LV_INDEV_STATE_REL;
    }
    else
    {
        data->state = LV_INDEV_STATE_PR;
        data->point.x = touchX;
        data->point.y = touchY;
    }
}

void lv_handler()
{
    static uint64_t previousUpdate = 0;
    static uint64_t interval = 0;

    uint64_t eus = esp_timer_get_time();
    if (eus - previousUpdate > interval)
    {
        previousUpdate = eus;
        interval = lv_timer_handler(); // Update the UI
        lv_tick_inc(interval);
        vTaskDelay(pdMS_TO_TICKS(interval - 1));
    }
}

void setup_fatfs()
{
    const esp_vfs_fat_mount_config_t mount_config = {
        .format_if_mount_failed = false,
        .max_files = 4,
        .allocation_unit_size = CONFIG_WL_SECTOR_SIZE,
        .disk_status_check_enable = false,
        .use_one_fat = false,
    };

    ESP_LOGI(TAG, "Mounting FAT filesystem in read/write mode");
    static wl_handle_t wl_handle = WL_INVALID_HANDLE;
    esp_err_t err = esp_vfs_fat_spiflash_mount_rw_wl(base_path, "storage", &mount_config, &wl_handle);

    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
        return;
    }

    FILE *f;
    ESP_LOGI(TAG, "Reading file");

    const char *host_filename1 = "/storage/response.png";

    struct stat info;
    struct tm timeinfo;
    char buffer[32];

    if (stat(host_filename1, &info) < 0)
    {
        ESP_LOGE(TAG, "Failed to read file stats");
        return;
    }
    localtime_r(&info.st_mtime, &timeinfo);
    strftime(buffer, sizeof(buffer), "%Y-%m-%d", &timeinfo);

    ESP_LOGI(TAG, "The file '%s' was modified at date: %s", host_filename1, buffer);

    f = fopen(host_filename1, "rb");
    if (f == NULL)
    {
        ESP_LOGE(TAG, "Failed to open file for reading");
        return;
    }
    fclose(f);

    ESP_LOGI(TAG, "Unmounting FAT filesystem");
    ESP_ERROR_CHECK(esp_vfs_fat_spiflash_unmount_rw_wl(base_path, wl_handle));
    ESP_LOGI(TAG, "Done");
}

void esp_lv_log_print(lv_log_level_t level, const char *buf)
{
    switch (level)
    {
    case LV_LOG_LEVEL_TRACE:
        ESP_LOGV("LVGL", "%s", buf);
        break;
    case LV_LOG_LEVEL_INFO:
        ESP_LOGI("LVGL", "%s", buf);
        break;
    case LV_LOG_LEVEL_WARN:
        ESP_LOGW("LVGL", "%s", buf);
        break;
    case LV_LOG_LEVEL_ERROR:
        ESP_LOGE("LVGL", "%s", buf);
        break;
    case LV_LOG_LEVEL_USER:
        ESP_LOGI("LVGL", "%s", buf);
        break;
    case LV_LOG_LEVEL_NONE:
        break;
    }
}

void setup()
{
    setup_fatfs();

    setup_tft();

    lv_init();

    lv_log_register_print_cb(esp_lv_log_print);

    static auto *display = lv_display_create(screenWidth, screenHeight);
    lv_display_set_color_format(display, LV_COLOR_FORMAT_RGB565);
    lv_display_set_flush_cb(display, flush);
    lv_display_set_buffers(display, lvBuffer1, lvBuffer2, lvBufferSize, LV_DISPLAY_RENDER_MODE_PARTIAL);

    static auto *lvInput = lv_indev_create();
    lv_indev_set_type(lvInput, LV_INDEV_TYPE_POINTER);
    lv_indev_set_read_cb(lvInput, my_touch_read);

    ESP_LOGI(TAG, "create image");
    static auto *image = lv_image_create(lv_scr_act());
    lv_image_set_src(image, &image_data);
    lv_obj_align(image, LV_ALIGN_TOP_LEFT, 0, 0);
    ESP_LOGI(TAG, "image created");
}

void loop()
{
    lv_handler();
}

void lvgl_task(void *pvParameter)
{
    setup();
    while (1)
    {
        loop();
    }
}

extern "C" void app_main(void)
{
    xTaskCreatePinnedToCore(lvgl_task, "lvgl_task", 4096, NULL, 5, NULL, 1);
}
