#include <stdio.h>
#include "pico/stdlib.h"
#include "common.h"
#include "mcu_hw.h"
#include "lcdspi_info.h"
#include "lcdspi.h"

// #define LCDSPI_ID   GMT130
#define LCDSPI_ID   QT095B

static const lcdspi_pins_t m_lcdspi_pins = {
#if defined(HW_LCDSPI_CLK)
    (uint32_t)HW_LCDSPI_CLK,
#else
    (uint32_t)PIN_NONE,
#endif
#if defined(HW_LCDSPI_MOSI)
    (uint32_t)HW_LCDSPI_MOSI,
#else
    (uint32_t)PIN_NONE,
#endif
#if defined(HW_LCDSPI_MISO)
    (uint32_t)HW_LCDSPI_MISO,
#else
    (uint32_t)PIN_NONE,
#endif
#if defined(HW_LCDSPI_CS)
    (uint32_t)HW_LCDSPI_CS,
#else
    (uint32_t)PIN_NONE,
#endif
#if defined(HW_LCDSPI_RESET)
    (uint32_t)HW_LCDSPI_RESET,
#else
    (uint32_t)PIN_NONE,
#endif
#if defined(HW_LCDSPI_RS)
    (uint32_t)HW_LCDSPI_RS,
#else
    (uint32_t)PIN_NONE,
#endif
};

static lcdspi_t m_lcdspi = {
    .spi_ch = 0,
    .gpio_output = (lcdspi_gpio_output_t)mcu_gpio_mode_output,
    .gpio_input = (lcdspi_gpio_input_t)mcu_gpio_mode_input,
    .gpio_write = (lcdspi_gpio_write_t)mcu_gpio_write,
    .gpio_read = (lcdspi_gpio_read_t)mcu_gpio_read,
    .spi_init = (lcdspi_spi_init_t)mcu_spi_init,
    .spi_transfer = (lcdspi_spi_transfer_t)mcu_spi_transfer,
    .baud = 16000000,
};

void camera_lcd_init(uint16_t x, uint16_t y, uint16_t width, uint16_t height) {
    lcdspi_init((lcdspi_t *)&m_lcdspi,
            (lcdspi_screen_t *)NULL,
            (lcdspi_pins_t *)&m_lcdspi_pins,
            (uint32_t)LCDSPI_ID, 0);
    int16_t sx = x;
    int16_t sy = y;
    int16_t ex = x + width;
    int16_t ey = y + height;
    sx -= 1;
    if (sx < (int16_t)m_lcdspi.lcd->sx) {
        sx = (int16_t)m_lcdspi.lcd->sx;
    }
    sy -= 1;
    if (sy < (int16_t)m_lcdspi.lcd->sy) {
        sy = (int16_t)m_lcdspi.lcd->sy;
    }
    ex += 1;
    if (ex > (int16_t)m_lcdspi.lcd->ex) {
        ex = (int16_t)m_lcdspi.lcd->ex;
    }
    ey += 1;
    if (ey > (int16_t)m_lcdspi.lcd->ey) {
        ey = (int16_t)m_lcdspi.lcd->ey;
    }
    lcdspi_box((lcdspi_t *)&m_lcdspi, sx, sy, ex, ey, 0xffff);
}

void camera_lcd_display(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint16_t *data) {

    lcdspi_bitbltex565((lcdspi_t *)&m_lcdspi, (uint32_t)x, (uint32_t)y, (uint32_t)width, (uint32_t)height, data);
}

