#include "mapView.h"

#include <esp_task_wdt.h>
#include <sys/time.h>
#include <time.h>
#include <cstring>
#include <string>
#include "epd_driver.h"
#include "fonts/opensans12b.h"
#include "fonts/opensans26b.h"
#include "fonts/opensans6.h"
#include "staticmap.h"
#include "utilities.h"

uint8_t* framebuffer;
GFXfont currentFont;

enum alignment { LEFT, RIGHT, CENTER };

void drawString(int32_t x, int32_t y, std::string text, alignment align) {
    char* data = const_cast<char*>(text.c_str());
    int32_t x1, y1;  // the bounds of x,y and w and h of the variable 'text' in
                     // pixels.
    int32_t w, h;
    int32_t xx = x, yy = y;
    get_text_bounds(&currentFont, data, &xx, &yy, &x1, &y1, &w, &h, NULL);
    if (align == RIGHT)
        x = x - w;
    if (align == CENTER)
        x = x - w / 2;
    int32_t cursor_y = y + h;
    int32_t padding = 4;
    epd_fill_rect(x - padding, y - padding, w + 2 * padding, h + 2 * padding, 255, framebuffer);
    write_string(&currentFont, data, &x, &cursor_y, framebuffer);
}

void drawVessel(int32_t x, int32_t y, std::string vesselName) {
    currentFont = OpenSans;
    int32_t radius = 10;
    epd_fill_circle(x, y, radius, 255, framebuffer);
    epd_draw_circle(x, y, radius, 0, framebuffer);
    drawString(x, y + 2 * radius, vesselName, CENTER);
}

void mapView(void* args) {
    framebuffer = (uint8_t*)heap_caps_malloc(EPD_WIDTH * EPD_HEIGHT / 2, MALLOC_CAP_SPIRAM);

    if (!framebuffer) {
        printf("alloc memory failed !!!");
        while (1) {
        }
    }

    std::memset(framebuffer, 0xFF, EPD_WIDTH * EPD_HEIGHT / 2);

    while (1) {
        int32_t width = staticmap_width;
        int32_t height = staticmap_height;
        const uint8_t* data = staticmap_data;

        Rect_t area = {.x = EPD_WIDTH - width, .y = 0, .width = width, .height = height};
        epd_copy_to_framebuffer(area, (uint8_t*)data, framebuffer);
        epd_draw_rect(area.x, area.y, area.width, area.height, 0, framebuffer);

        int32_t x = area.x / 2;
        int32_t y = 26;
        currentFont = OpenSans26B;
        drawString(x, y, "Tide Display", CENTER);

        time_t now;
        struct tm timeinfo;
        char strftime_buf[64];

        currentFont = OpenSans12B;
        time(&now);
        localtime_r(&now, &timeinfo);
        strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        drawString(area.x / 2, area.height - 33, strftime_buf, CENTER);

        drawVessel(EPD_WIDTH - EPD_WIDTH / 4, EPD_HEIGHT - EPD_HEIGHT / 5, "DEEPENSCHRIEWER 1");

        epd_poweron();
        epd_clear();
        epd_draw_grayscale_image(epd_full_screen(), framebuffer);
        epd_poweroff_all();

        vTaskDelay(pdMS_TO_TICKS(60000));
    }
}
