#include "display.h"
#include "widgets/label/lv_label.h"

#include <esp_log.h>
#include <esp_lcd_panel_ops.h>
#include <esp_heap_caps.h>
#include <esp_lcd_panel_io.h>
#include <esp_timer.h>
#include <lv_init.h>
#include <display/lv_display.h>
#include <driver/i2c_master.h>
#include <mutex>

// To use LV_COLOR_FORMAT_I1 we need an extra buffer to hold the converted data.
uint8_t Display::oled_buffer_[LCD_H_RES * LCD_V_RES / 8];

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

Display::Display(const I2C &i2c) :
    panel_(i2c)
{
  if (!lv_is_initialized()) {
    ESP_LOGI(TAG, "Initialize LVGL");
    lv_init();
  }

  // Create a lvgl display.
  // TODO: Use PanelDevice functions
  display_ = lv_display_create(LCD_H_RES, LCD_V_RES);
  // associate the i2c panel handle to the display
  lv_display_set_user_data(display_, panel_.get());
  // Create draw buffer.
  ESP_LOGI(TAG, "Allocate separate LVGL draw buffers");
  // TODO: Use PanelDevice functions
  size_t draw_buffer_sz = LCD_H_RES * LCD_V_RES / 8 + LVGL_PALETTE_SIZE;
  buf_ = heap_caps_calloc(1, draw_buffer_sz,
                          MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  assert(buf_);

  // LVGL9 suooprt new monochromatic format.
  lv_display_set_color_format(display_, LV_COLOR_FORMAT_I1);
  // Initialize LVGL draw buffers.
  lv_display_set_buffers(display_, buf_, nullptr, draw_buffer_sz,
                         LV_DISPLAY_RENDER_MODE_FULL);
  lv_display_set_rotation(display_, LV_DISPLAY_ROTATION_0);
  // Set callback which can copy the rendered image to an area of the display.
  lv_display_set_flush_cb(display_, Display::lvgl_flush_cb);

  ESP_LOGI(TAG,
           "Register io panel event callback for LVGL flush ready notification");
  const esp_lcd_panel_io_callbacks_t cbs = {
      .on_color_trans_done = Display::lvgl_flush_ready,
  };
  /* Register done callback */
  ESP_ERROR_CHECK(
      esp_lcd_panel_io_register_event_callbacks(panel_.io_handle_, &cbs,
                                                display_));

  // TODO: What is this
  ESP_LOGI(TAG, "Use esp_timer as LVGL tick timer");
  const esp_timer_create_args_t lvgl_tick_timer_args = {
      .callback = &Display::lvgl_increase_tick,
      .name = "lvgl_tick"
  };
  esp_timer_handle_t lvgl_tick_timer = nullptr;
  ESP_ERROR_CHECK(esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer));
  ESP_ERROR_CHECK(esp_timer_start_periodic(lvgl_tick_timer,
                                           LVGL_TICK_PERIOD_MS * 1000));

  ESP_LOGI(TAG, "Create LVGL task");
  xTaskCreate(Display::lvgl_port_task, "LVGL", LVGL_TASK_STACK_SIZE,
              nullptr, LVGL_TASK_PRIORITY, nullptr);
}

void Display::set_text(const char *text,
                       const char *name,
                       lv_label_long_mode_t long_mode,
                       lv_align_t align)
{
  // Lock the mutex due to the LVGL APIs are not thread-safe.
  ScopedLock lock;

  ESP_LOGI(TAG, "Display LVGL Scroll Text");
  lv_obj_t *scr = lv_display_get_screen_active(display_);
  objects_[name] = lv_label_create(scr);
  // Circular scroll
  lv_label_set_long_mode(objects_[name], long_mode);
  lv_label_set_text(objects_[name], text);

  // Set the size of the screen.
  // If you use rotation 90 or 270 use lv_display_get_vertical_resolution.
  lv_obj_set_width(objects_[name],
                   lv_display_get_horizontal_resolution(display_));
  lv_obj_align(objects_[name], align, 0, 0);
}

bool Display::lvgl_flush_ready(esp_lcd_panel_io_handle_t,
                               esp_lcd_panel_io_event_data_t *,
                               void *user_ctx)
{
  auto *disp = (lv_display_t *) user_ctx;
  lv_display_flush_ready(disp);
  return false;
}

void Display::lvgl_flush_cb(lv_display_t *display, const lv_area_t *area,
                            uint8_t *px_map)
{
  auto 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.
  // 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;

  for (int32_t y = y1; y <= y2; y++) {
    for (int32_t x = x1; x <= x2; x++) {
      /* The order of bits 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
      */
      bool chroma_color = (px_map[(hor_res >> 3) * y + (x >> 3)] &
                           1 << (7 - x % 8));

      // Write to the buffer as required for the display.
      // It writes only 1-bit for monochrome displays mapped vertically.
      uint8_t *buf = oled_buffer_ + hor_res * (y >> 3) + (x);
      if (chroma_color) {
        (*buf) &= ~(1 << (y % 8));
      } else {
        (*buf) |= (1 << (y % 8));
      }
    }
  }
  // Pass the draw buffer to the driver.
  ESP_ERROR_CHECK(
      esp_lcd_panel_draw_bitmap(panel_handle, x1, y1, x2 + 1, y2 + 1,
                                oled_buffer_));
}

void Display::lvgl_increase_tick(void *)
{
  // Tell LVGL how many milliseconds has elapsed
  lv_tick_inc(LVGL_TICK_PERIOD_MS);
}

void Display::lvgl_port_task(void *)
{
  ESP_LOGI(TAG, "Starting LVGL task");
  uint32_t time_till_next_ms = 0;
  while (1) {
    _lock_acquire(&ScopedLock::lock_);
    time_till_next_ms = lv_timer_handler();
    _lock_release(&ScopedLock::lock_);
    usleep(1000 * time_till_next_ms);
  }
}

I2C::I2C() : i2c_bus_(nullptr)
{
  ESP_LOGI(TAG, "Initialize I2C bus");
  i2c_master_bus_config_t bus_config = {
      .i2c_port = I2C_BUS_PORT,
      .sda_io_num = PIN_SDA,
      .scl_io_num = PIN_SCL,
      .clk_source = I2C_CLK_SRC_DEFAULT,
      .glitch_ignore_cnt = 7,
      .flags {
          .enable_internal_pullup = true,
      },
  };
  ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &i2c_bus_));
}

Panel::Panel(i2c_master_bus_handle_t i2c) : io_handle_(nullptr), panel_(nullptr)
{
  ESP_LOGI(TAG, "Install panel IO");
  esp_lcd_panel_io_i2c_config_t io_config = {
      .dev_addr = I2C_HW_ADDR,
      .control_phase_bytes = 1,               // According to SSD1306 datasheet
      .dc_bit_offset = 6,                     // According to SSD1306 datasheet
      .lcd_cmd_bits = LCD_CMD_BITS,           // According to SSD1306 datasheet
      .lcd_param_bits = LCD_CMD_BITS,         // According to SSD1306 datasheet
      .scl_speed_hz = LCD_PIXEL_CLOCK_HZ,
  };
  ESP_ERROR_CHECK(
      esp_lcd_new_panel_io_i2c(i2c, &io_config, &io_handle_));

  ESP_LOGI(TAG, "Install SSD1306 panel driver");
  SSD1306 ssd1306({.height = LCD_V_RES});
  panel_config_ = {
      .reset_gpio_num = PIN_RST,
      .bits_per_pixel = 1,
  };
  ssd1306.create_panel(panel_config_, io_handle_, panel_);

  ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_));
  ESP_ERROR_CHECK(esp_lcd_panel_init(panel_));
  ESP_ERROR_CHECK(esp_lcd_panel_disp_on_off(panel_, true));
}

SSD1306::SSD1306(esp_lcd_panel_ssd1306_config_t ssd_config,
                 int width,
                 int height) :
    PanelDevice<esp_lcd_panel_ssd1306_config_t>(width, height)
{
  vendor_config_ = ssd_config;
}
