#include "main.h"
#include "display_gfx.h"
#include "st7565.h"
// #include "spi.h"
#include "string.h"

static uint8_t st7565_buffor[ST7565_BUFFER_SIZE];

static void ST7565_SendCommand(st7565_handle_t *hdisp, uint8_t data)
{
    HAL_GPIO_WritePin(hdisp->a0_port, hdisp->a0_pin, GPIO_PIN_RESET);

    HAL_SPI_Transmit(hdisp->hspi, &data, 1, HAL_MAX_DELAY);
}

static void ST7565_SendData(st7565_handle_t *hdisp, uint8_t *data, uint16_t size)
{
    HAL_GPIO_WritePin(hdisp->a0_port, hdisp->a0_pin, GPIO_PIN_SET);

    HAL_SPI_Transmit(hdisp->hspi, data, size, HAL_MAX_DELAY);
}

void ST7565_Init(st7565_handle_t *hdisp, GFX_display_t *disp)
{
    if (hdisp == NULL || hdisp->hspi == NULL || hdisp->a0_port == NULL || hdisp->cs_port == NULL || hdisp->rst_port == NULL)
    {
        Error_Handler();
    }

    disp->width = ST7565_WIDTH;
    disp->height = ST7565_HEIGHT;
    disp->buffor = st7565_buffor;
    // toggle RST low to reset; CS low so it'll listen to us
    HAL_GPIO_WritePin(hdisp->cs_port, hdisp->cs_pin, GPIO_PIN_RESET);

    HAL_GPIO_WritePin(hdisp->rst_port, hdisp->rst_pin, GPIO_PIN_RESET);
    HAL_Delay(500);
    HAL_GPIO_WritePin(hdisp->rst_port, hdisp->rst_pin, GPIO_PIN_SET);

    // LCD bias select
    ST7565_SendCommand(hdisp, CMD_SET_BIAS_7);
    // ADC select
    ST7565_SendCommand(hdisp, CMD_SET_ADC_REVERSE);
    // SHL select
    ST7565_SendCommand(hdisp, CMD_SET_COM_NORMAL);
    // Initial display line
    ST7565_SendCommand(hdisp, CMD_SET_DISP_START_LINE);

    // turn on voltage converter (VC=1, VR=0, VF=0)
    ST7565_SendCommand(hdisp, CMD_SET_POWER_CONTROL | 0x4);
    // wait for 50% rising
    HAL_Delay(50);

    // turn on voltage regulator (VC=1, VR=1, VF=0)
    ST7565_SendCommand(hdisp, CMD_SET_POWER_CONTROL | 0x6);
    // wait >=50ms
    HAL_Delay(50);

    // turn on voltage follower (VC=1, VR=1, VF=1)
    ST7565_SendCommand(hdisp, CMD_SET_POWER_CONTROL | 0x7);
    // wait
    HAL_Delay(10);

    // set lcd operating voltage (regulator resistor, ref voltage resistor)
    ST7565_SendCommand(hdisp, CMD_SET_RESISTOR_RATIO | 0x6);

    ST7565_SendCommand(hdisp, CMD_DISPLAY_ON);
    ST7565_SendCommand(hdisp, CMD_SET_ALLPTS_NORMAL);
    ST7565_SendCommand(hdisp, CMD_SET_VOLUME_FIRST);
    ST7565_SendCommand(hdisp, CMD_SET_VOLUME_SECOND | (0x00 & 0x3f));

    HAL_GPIO_WritePin(hdisp->cs_port, hdisp->cs_pin, GPIO_PIN_SET);
}

void ST7565_DisplayAll(st7565_handle_t *hdisp)
{
    HAL_GPIO_WritePin(hdisp->cs_port, hdisp->cs_pin, GPIO_PIN_RESET);
    for (uint8_t p = 0; p < 8; p++)
    {
        ST7565_SendCommand(hdisp, CMD_SET_PAGE | p);
        ST7565_SendCommand(hdisp, CMD_SET_COLUMN_UPPER | 0);
        ST7565_SendCommand(hdisp, CMD_SET_COLUMN_LOWER | 0);

        ST7565_SendData(hdisp, &st7565_buffor[128 * p], 128);
    }
    HAL_GPIO_WritePin(hdisp->cs_port, hdisp->cs_pin, GPIO_PIN_SET);
}
