/*#############################################################################
## Author: Shaun Reed                                                        ##
## Legal: All Content (c) 2025 Shaun Reed, all rights reserved               ##
##                                                                           ##
## Contact: shaunrd0@gmail.com  | URL: www.shaunreed.com                     ##
##############################################################################
*/
#ifndef PANEL_DEVICE_H
#define PANEL_DEVICE_H

#include <esp_lcd_panel_dev.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_log.h>
#include <esp_timer.h>

#include <sys/unistd.h>

#include <i2c.h>
#include <pixel.h>

static esp_timer_handle_t esp_timer_;

#include <display/lv_display.h>

/// Tag used for ESP logging.
static const char* LCD_TAG = "LCD component";

// LVGL library is not thread-safe, this example calls LVGL APIs from tasks.
// We must use a mutex to protect it.
static _lock_t lv_lock_;

// LVGL reserves 2x4 bytes in the buffer to be used as a palette.
// This additional space must be added to the IPanelDevice::buf_size_.
#define LVGL_PALETTE_SIZE 8
#define LVGL_TICK_PERIOD_MS 5
#define LVGL_TASK_STACK_SIZE (4 * 1024)
#define LVGL_TASK_PRIORITY 2

#define LCD_H_RES 128
#define LCD_V_RES 64

// According to specific display hardware.
// https://www.digikey.com/en/products/detail/winstar-display/WEA012864DWPP3N00003/20533255
#define SCREEN_WIDTH 128 // OLED display width, in pixels.
#define SCREEN_HEIGHT 64 // OLED display height, in pixels.

// According to SSD1306 datasheet.
// https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf
#define I2C_HW_ADDR 0x3C
#define LCD_PIXEL_CLOCK_HZ (400 * 1000)
// Bit number used to represent command and parameter
#define LCD_CMD_BITS 8
#define LCD_PARAM_BITS 8

/**
 * Retrieve the device specific vendor configuration structure.
 *
 * @return Address of vendor configuration structure.
 */
typedef void* (*vendor_config_cb_t)();

/**
 * Registers LVGL ticker timer callback for rendering this display.
 *
 * An implementation of the interface can optionally override this method to
 * provide custom LVGL callbacks and tick configurations.
 */
typedef void (*register_lvgl_tick_timer_cb_t)();

/**
 * Initializes the ESP panel using vendor specific APIs and configurations.
 * This method should implement any setup logic specific to the device.
 *
 * @param config ESP LCD panel configuration.
 * @param io ESP LCD panel IO handle.
 * @param [out] panel ESP LCD panel handle output pointer location.
 */
typedef void (*init_panel_cb_t)(esp_lcd_panel_dev_config_t* config,
                                esp_lcd_panel_io_handle_t io,
                                esp_lcd_panel_handle_t* panel);

/**
 * Registers LVGL draw buffers and callbacks for this display.
 *
 * An implementation of the interface can optionally override this method to
 * provide custom LVGL callbacks and display configurations.
 *
 * @param display_handle LVGL display handle to use for rendering.
 * @param io_handle IO handle for the ESP LCD panel.
 */
typedef void (*register_rendering_data_cb_t)(
    lv_display_t* display_handle, esp_lcd_panel_io_handle_t io_handle, void*,
    size_t);

/**
 * Encapsulates vendor specific ESP LCD panel initialization logic.
 * This pure virtual interface can be inherited from for using new LCD devices.
 * See SSD1306 as an example to implement IPanelDevice for NT35510 or ST7789.
 *
 * At this time only I2C is supported.
 * Classes that inherit from this interface should likely be marked final.
 */
struct IPanelDevice
{
    /// Width of the device screen in pixels.
    int32_t width_;

    /// Height of the device screen in pixels.
    int32_t height_;

    /// RST GPIO pin number.
    int rst_num_;

    /// LVGL draw buffer size for the device.
    size_t lv_buf_size_;

    /// ESP LCD panel IO configuration.
    esp_lcd_panel_io_i2c_config_t esp_io_config_;

    /// LVGL draw buffer associated with this Display's lv_display_t.
    void* lv_buf_;

    /// Callback used to initialize the ESP panel.
    init_panel_cb_t init_panel_cb;

    /// Callback used to register LVGL tick timer.
    register_lvgl_tick_timer_cb_t register_lvgl_tick_timer_cb;

    /// Callback used to register LVGL draw buffers.
    register_rendering_data_cb_t register_rendering_data_cb;

    /// Callback used to fetch the display vendor configuration.
    vendor_config_cb_t vendor_config_cb;
};

/**
 * Static accessor to a static buffer to store draw buffer data for the panel.
 *
 * This method is protected to allow an implementation to provide a custom
 * callback method similar to IPanelDevice::lvgl_flush_cb.
 *
 * The buffer is allocated statically within the scope of this function to
 * allow creating multiple panels that _each_ manage their own statically
 * allocated draw buffer data. This simplifies implementing the interface by
 * taking this responsibility off of the implementor. The buffer will only be
 * allocated if this method is called, so the memory is only used if required.
 *
 * @return Pointer to uint8 draw buffer data.
 * @sa register_rendering_data for overriding LVGL rendering callbacks.
 */
static uint8_t* get_additional_draw_buffer()
{
    // Static to the scope of this function, not the compilation unit.
    // For LV_COLOR_FORMAT_I1 we need an extra buffer to hold converted data.
    static uint8_t oled_buffer[LCD_H_RES * LCD_V_RES / 8];
    return oled_buffer;
}

/**
 * The callback invoked when panel IO finishes transferring color data.
 * This signals that the panel is ready to flush image data to the display.
 *
 * @param panel LCD panel IO handles.
 * @param data Panel IO event data, fed by driver.
 * @param user_ctx User data, passed from `esp_lcd_panel_io_xxx_config_t`.
 * @return Whether a high priority task has been waken up by this function.
 * @sa register_rendering_data for overriding this callback.
 */
static bool lvgl_flush_ready_cb(esp_lcd_panel_io_handle_t,
                                esp_lcd_panel_io_event_data_t*,
                                void* user_ctx)
{
    lv_display_t* disp = (lv_display_t*)user_ctx;
    lv_display_flush_ready(disp);
    return false;
}

/**
 * The callback invoked for flushing the rendered image to the display.
 *
 * `px_map` contains the rendered image as raw pixel map and it should be
 *  copied to `area` on the display.
 *
 * The following details are crucial for understanding the logic surrounding
 * flushing to the display in this example.
 *
 * The order of bits within the px_map from _LVGL_ is MSB first.
 *              MSB           LSB
 *     bits      7 6 5 4 3 2 1 0
 *     pixels    0 1 2 3 4 5 6 7
 *              Left         Right
 *
 * The bytes from _LVGL_ are mapped to pixel rows of the display
 * 8 bits (pixels) per byte -
 * [0, 0, 0, 0, 0, 0, 0, 0]
 * [0, 0, 0, 0, 0, 0, 0, 0]
 * [0, 0, 0, 0, 0, 0, 0, 0]
 *
 * The order of bits expected by the _display driver_ is LSB first.
 * We must preserve pairing of each bit and pixel when writing to the display.
 *              LSB           MSB
 *     bits      0 1 2 3 4 5 6 7
 *     pixels    7 6 5 4 3 2 1 0
 *              Left         Right
 *
 * Bytes expected by the _display driver_ map to pixel columns of the display.
 * 8 bits (pixels) per byte -
 * [0, [0, [0, [0,
 *  0,  0,  0,  0,
 *  0,  0,  0,  0,
 *  0,  0,  0,  0,
 *  0,  0,  0,  0,
 *  0,  0,  0,  0,
 *  0,  0,  0,  0,
 *  0]  0]  0]  0]
 *
 * These layouts in memory have no opinion on the shape of the image. The
 * beginning and end of a row or a column for example is entirely dependent
 * on how the data is accessed. The vertical and horitzontal resolution may
 * vary between displays.
 *
 * For the LV_COLOR_FORMAT_I1 color format we are using, an additional buffer
 * is needed for transposing the bits to the vertical arrangement required by
 * the display driver that is outlined above.
 *
 * This callback implementation is an example of handling this transposition
 * and flushing the data to the display in the expected format.
 *
 * @param display LVGL display handle to use for rendering.
 * @param area Area of the display being flushed.
 * @param px_map Rendered image data for writing to the display area.
 * @sa register_rendering_data for overriding this callback.
 * @sa get_additional_draw_buffer
 */
static void lvgl_flush_cb(lv_display_t* display, const lv_area_t* area,
                          uint8_t* px_map)
{
    esp_lcd_panel_handle_t panel_handle =
        (esp_lcd_panel_handle_t)lv_display_get_user_data(display);

    // Necessary because LVGL reserves 2x4 bytes in the buffer for a palette.
    // Since we are monochrome, we don't need these additional bytes.
    // For more information about the monochrome, please refer to:
    // https://docs.lvgl.io/9.2/porting/display.html#monochrome-displays
    // Skip the palette here.
    px_map += LVGL_PALETTE_SIZE;

    uint16_t hor_res = lv_display_get_physical_horizontal_resolution(display);
    int32_t x1 = area->x1;
    int32_t x2 = area->x2;
    int32_t y1 = area->y1;
    int32_t y2 = area->y2;


    // As of 03/01/2025 master branch of LVGL contains this helper for the same.
    // https://docs.lvgl.io/master/API/draw/sw/lv_draw_sw_utils.html
    // lv_draw_sw_i1_convert_to_vtiled()
    for (int32_t y = y1; y <= y2; y++)
    {
        for (int32_t x = x1; x <= x2; x++)
        {
            // Get the byte offset of the pixel coordinates using
            // horizontal-mapping.
            int h_offset = horizontal_byte_offset_long(x, y, hor_res);
            // True if the pixel is lit, else false.
            bool chroma_color = px_map[h_offset] & msb_mask(x);

            // We need an additional buffer for transposing the pixel data to
            // the vertical format required by the display driver.
            uint8_t* buf = get_additional_draw_buffer();
            // Move to the position in the auxillary buffer where the pixel is
            // stored.
            buf += vertical_byte_offset_long(x, y, hor_res);

            // Write the single bit to the monochrome display mapped vertically.
            // Take the Least Significant Bit mask of the Y coordinate to select
            // the bit representing a pixel at position y in a vertically-mapped
            // display.
            if (chroma_color)
            {
                // Set the vertically-mapped pixel to on.
                *buf &= ~lsb_mask(y);
            }
            else
            {
                // Set the vertically-mapped pixel to off.
                *buf |= lsb_mask(y);
            }
        }
    }
    // Pass the draw buffer to the driver.
    ESP_ERROR_CHECK(esp_lcd_panel_draw_bitmap(
        panel_handle, x1, y1, x2 + 1, y2 + 1, get_additional_draw_buffer()));
}

/**
 * Callback invoked for every period of the timer.
 *
 * This callback _must_ call lv_tick_inc to inform LVGL how much time has
 * elapsed since the last period of the timer.
 *
 * @param data User data passed to the callback.
 * @sa register_lvgl_tick_timer for setting user data and the tick period of
 *        the timer, or overriding this callback entirely.
 */
static void lvgl_increase_tick_cb(void*)
{
    // Tell LVGL how many milliseconds has elapsed
    lv_tick_inc(LVGL_TICK_PERIOD_MS);
}

/**
 * FreeRTOS task callback invoked for handling LVGL events or updating the UI.
 *
 * This function is intentionally an endless loop and should never return.
 * LVGL initialization logic can optionally be added before entering the loop.
 * Input logic can optionally be handled within the loop.
 *
 * This callback _must_ call lv_timer_handler to handle LVGL periodic timers.
 *
 * @param data User data passed to the callback.
 * @sa register_lvgl_tick_timer for overriding this callback.
 */
[[noreturn]] static void lvgl_port_task(void*)
{
    // Optionally initialize some LVGL objects here before entering loop below.

    ESP_LOGI(LCD_TAG, "Starting LVGL task");
    for (uint32_t time_to_next_ms = 0; true; usleep(1000 * time_to_next_ms))
    {
        // Obtain LVGL API lock before calling any LVGL methods.
        _lock_acquire(&lv_lock_);

        // Optionally handle LVGL input or event logic here.

        // Update LVGL periodic timers.
        time_to_next_ms = lv_timer_handler();

        _lock_release(&lv_lock_);
    }
}

/**
 * Registers LVGL ticker timer callback for rendering this display.
 *
 * An implementation of the interface can optionally override this method to
 * provide custom LVGL callbacks and tick configurations.
 */
static void register_lvgl_tick_timer()
{
    ESP_LOGI(LCD_TAG, "Use esp_timer to increase LVGL tick");
    const esp_timer_create_args_t esp_timer_args = {
        .callback = &lvgl_increase_tick_cb,
        // Data to pass to the lvgl_port_task callback.
        .arg = NULL,
        .name = "lvgl_tick",
    };

    /// Start periodic ESP timer handle.
    ESP_LOGI(LCD_TAG, "Creating esp_timer with name: '%s'",
             esp_timer_args.name);
    ESP_ERROR_CHECK(esp_timer_create(&esp_timer_args, &esp_timer_));
    ESP_ERROR_CHECK(
        esp_timer_start_periodic(esp_timer_, LVGL_TICK_PERIOD_MS * 1000));
    ESP_LOGI(LCD_TAG, "Starting esp_timer with name: '%s'",
             esp_timer_args.name);

    // LVGL requires a FreeRTOS task for running it's event loop.
    // The lvgl_port_task callback can update the UI or handle input logic.
    // For this basic example we don't do either of these things.
    ESP_LOGI(LCD_TAG, "Create LVGL FreeRTOS task");
    // Optionally set user data to pass to LVGL's FreeRTOS task callback here.
    void* user_data = NULL;
    xTaskCreate(lvgl_port_task, "LVGL", LVGL_TASK_STACK_SIZE, user_data,
                LVGL_TASK_PRIORITY, NULL);
}

static void register_rendering_data(lv_display_t* display_handle,
                                    esp_lcd_panel_io_handle_t io_handle,
                                    void* lv_buf, size_t lv_buf_size)
{
    // Create draw buffer.
    ESP_LOGI(LCD_TAG, "Allocate separate LVGL draw buffers");
    lv_buf =
        heap_caps_calloc(1, lv_buf_size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
    assert(lv_buf);

    ESP_LOGI(LCD_TAG, "Set LVGL draw buffers");
    // Color format must be set first, LVGL9 support new monochromatic format.
    lv_display_set_color_format(display_handle, LV_COLOR_FORMAT_I1);
    lv_display_set_buffers(display_handle, lv_buf, NULL, lv_buf_size,
                           LV_DISPLAY_RENDER_MODE_FULL);
    lv_display_set_rotation(display_handle, LV_DISPLAY_ROTATION_0);

    ESP_LOGI(LCD_TAG, "Set LVGL callback for flushing to the display");
    lv_display_set_flush_cb(display_handle, lvgl_flush_cb);

    ESP_LOGI(LCD_TAG,
             "Register io panel callback for LVGL flush ready notification");
    const esp_lcd_panel_io_callbacks_t cbs = {
        .on_color_trans_done = lvgl_flush_ready_cb,
    };
    ESP_ERROR_CHECK(esp_lcd_panel_io_register_event_callbacks(io_handle, &cbs,
                                                              display_handle));
}

/// Callback used to fail, indicating the device is not fully initialized.
static void* fail_vendor_config_cb()
{
    ESP_LOGE(LCD_TAG, "Callback is unset: IPanelDevice::vendor_config_cb");
    assert(false);
}


/// Callback used to fail, indicating the device is not fully initialized.
static void fail_init_panel_cb(esp_lcd_panel_dev_config_t*,
                               esp_lcd_panel_io_handle_t,
                               esp_lcd_panel_handle_t*)
{
    ESP_LOGE(LCD_TAG, "Callback is unset: IPanelDevice::init_panel_cb");
    assert(false);
}

static struct IPanelDevice LCD_new_panel()
{
    return (struct IPanelDevice){
        .width_ = LCD_H_RES,
        .height_ = LCD_V_RES,
        .rst_num_ = I2C_DEFAULT_PIN_RST,
        .lv_buf_size_ = LCD_H_RES * LCD_V_RES / 8 + LVGL_PALETTE_SIZE,
        .esp_io_config_ =
            (esp_lcd_panel_io_i2c_config_t){
                .dev_addr = I2C_HW_ADDR,
                // User data to pass to the LVGL flush_ready callback.
                // See IPanelDevice::lvgl_flush_ready_cb
                .user_ctx = NULL,
                .control_phase_bytes = 1,
                .dc_bit_offset = 6,
                .lcd_cmd_bits = LCD_CMD_BITS,
                .lcd_param_bits = LCD_PARAM_BITS,
                .scl_speed_hz = LCD_PIXEL_CLOCK_HZ,
            },
        .init_panel_cb = fail_init_panel_cb, // Must be assigned by caller
        .register_lvgl_tick_timer_cb = register_lvgl_tick_timer,
        .register_rendering_data_cb = register_rendering_data,
        .vendor_config_cb = fail_vendor_config_cb, // Must be assigned by caller
    };
}

#endif // PANEL_DEVICE_H
