#include <ch32v00x.h>
#include "clib/u8x8.h"
#include <debug.h>

#define BLINKY_GPIO_PORT GPIOD
#define BLINKY_GPIO_PIN GPIO_Pin_6
#define BLINKY_CLOCK_ENABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE)

void NMI_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void HardFault_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));

#define SECTOR_ADDR 0x08003c00 
#define PAGE_SIZE         64
#define NUM_PAGES         16
#define RECORDS_PER_PAGE  16

int8_t  active_page = -1;
int32_t active_page_id = -1;
uint16_t current_write_index = 0;
uint32_t current_value = 0;

void RingBuffer_FormatAll(void) {
    __disable_irq();
    FLASH_Unlock();
    // Erase entire 1KB sector
    FLASH_ErasePage(SECTOR_ADDR);
    FLASH_ProgramWord(SECTOR_ADDR, 1); // Write page identifier to 1
    FLASH_Lock();
    __enable_irq();
    // Set active page to first    
    active_page = 0;
    active_page_id = 1;
    current_write_index = 1;
    current_value = 0;
}

void RingBuffer_lastValueFrom(uint8_t page, uint32_t *out_value, uint16_t *out_index) {
    uint32_t *page_ptr = (uint32_t*)(SECTOR_ADDR + (page * PAGE_SIZE));
    *out_index = 0;
    for (int i = 1; i < RECORDS_PER_PAGE; i++) {
        if (page_ptr[i] == 0xFFFFFFFF) {
            break;
        }
        *out_value = page_ptr[i];
        *out_index = i + 1;
    }
}

void RingBuffer_Init(void) {
    // Search for page with maximum index
    for (int i = 0; i < NUM_PAGES; i++) {
        int32_t *page_ptr = (int32_t*)(SECTOR_ADDR + (i * PAGE_SIZE));
        int32_t page_id = page_ptr[0];
        if (page_id != 0xFFFFFFFF && page_id > active_page_id) {
            active_page = i;
            active_page_id = page_id;
        }
    }
    if (active_page == -1) {
        // If no active page found, format entire buffer
        RingBuffer_FormatAll();
        return;
    }
    // If active page found, try to read value from it
    current_write_index = 0;
    current_value = 0;
    RingBuffer_lastValueFrom(active_page, &current_value, &current_write_index);

    if (current_write_index == 0) {
        // Page is empty, which is strange
        // So we read from previous page if it exists
        active_page = (active_page - 1) % NUM_PAGES;
        RingBuffer_lastValueFrom(active_page, &current_value, &current_write_index);
        if (current_write_index == 0) {
            // If previous page is also empty, this is a strange situation
            // Format everything
            RingBuffer_FormatAll();
            return;
        }
    } else {
        current_write_index++;
    }
}

void RingBuffer_Write(uint32_t new_value) {
    if (new_value == current_value) return; 
    if (new_value == 0xFFFFFFFF) return; 

    __disable_irq(); 
    FLASH_Unlock_Fast();

    if (current_write_index >= RECORDS_PER_PAGE) {
        // Move to new page
        uint8_t next_page = (active_page + 1) % NUM_PAGES;
        uint32_t next_page_addr = SECTOR_ADDR + (next_page * PAGE_SIZE);
        // Format it
        FLASH_ErasePage_Fast(next_page_addr);
        // Set new page as active before writing new value
        active_page = next_page;
        active_page_id++;
        FLASH_Status st = FLASH_ProgramWord(next_page_addr, active_page_id); // Update active page identifier
        current_write_index = 1; // Start writing from beginning of new page
    }

    uint32_t write_addr = SECTOR_ADDR + (active_page * PAGE_SIZE) + (current_write_index * 4);
    FLASH_Status st = FLASH_ProgramWord(write_addr, new_value);
    FLASH_Lock_Fast();
    __enable_irq();
    current_value = new_value;
    current_write_index++;
}

// u8x8 functions
uint8_t u8x8_gpio_and_delay_ch32v(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) {
    switch(msg) {
        case U8X8_MSG_GPIO_AND_DELAY_INIT:
            RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
            GPIO_InitTypeDef init = {0};
            init.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
            init.GPIO_Mode = GPIO_Mode_Out_OD;
            init.GPIO_Speed = GPIO_Speed_50MHz;
            GPIO_Init(GPIOC, &init);
            break;
        case U8X8_MSG_DELAY_MILLI:
            Delay_Ms(arg_int);
            break;
        case U8X8_MSG_DELAY_10MICRO:
            for (volatile uint32_t i = 0; i < (arg_int * 8); i++) { __NOP(); }
            break;
        case U8X8_MSG_DELAY_100NANO:
            __NOP();
            break;

        case U8X8_MSG_GPIO_I2C_CLOCK:
            GPIO_WriteBit(GPIOC, GPIO_Pin_2, (BitAction)(arg_int ? Bit_SET : Bit_RESET));
            break;

        case U8X8_MSG_GPIO_I2C_DATA:
            GPIO_WriteBit(GPIOC, GPIO_Pin_1, (BitAction)(arg_int ? Bit_SET : Bit_RESET));
            break;
    }
    return 1;
}

uint8_t u8x8_byte_hw_i2c_ch32v(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) {
    uint8_t *data;
    switch(msg) {
        case U8X8_MSG_BYTE_INIT:
            RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE);
            RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);

            // We will use PC1 (SDA) and PC2 (SCL)
            GPIO_InitTypeDef GPIO_InitStructure = {0};
            GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
            GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD; // Alternate Function Open-Drain
            GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
            GPIO_Init(GPIOC, &GPIO_InitStructure);

            I2C_InitTypeDef I2C_InitTSturcture = {0};
            I2C_InitTSturcture.I2C_ClockSpeed = 1600000; // 400 kHz
            I2C_InitTSturcture.I2C_Mode = I2C_Mode_I2C;
            I2C_InitTSturcture.I2C_DutyCycle = I2C_DutyCycle_2;
            I2C_InitTSturcture.I2C_OwnAddress1 = 0x00;
            I2C_InitTSturcture.I2C_Ack = I2C_Ack_Enable;
            I2C_InitTSturcture.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
            I2C_Init(I2C1, &I2C_InitTSturcture);
            I2C_Cmd(I2C1, ENABLE);
            break;

        case U8X8_MSG_BYTE_START_TRANSFER:
            while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY) != RESET);

            I2C_GenerateSTART(I2C1, ENABLE);
            while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)); // Wait for EV5

            I2C_Send7bitAddress(I2C1, u8x8_GetI2CAddress(u8x8), I2C_Direction_Transmitter);
            while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); // Wait for EV6
            break;

        case U8X8_MSG_BYTE_SEND:
            data = (uint8_t *)arg_ptr;
            while (arg_int > 0) {
                I2C_SendData(I2C1, *data++);
                while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
                arg_int--;
            }
            break;

        case U8X8_MSG_BYTE_END_TRANSFER:
            I2C_GenerateSTOP(I2C1, ENABLE);
            break;
        default:
            break;
    }
    return 1;
}

int main(void) {
    SystemCoreClockUpdate();
    Delay_Init();
    USART_Printf_Init(9600);

    GPIO_InitTypeDef GPIO_InitStructure = {0};
    BLINKY_CLOCK_ENABLE;
    GPIO_InitStructure.GPIO_Pin = BLINKY_GPIO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(BLINKY_GPIO_PORT, &GPIO_InitStructure);

    // u8x8 initialization block
    u8x8_t u8x8;
    u8x8_Setup(&u8x8, 
        u8x8_d_ssd1306_128x32_univision, 
        u8x8_cad_ssd13xx_i2c, 
        u8x8_byte_hw_i2c_ch32v, 
        u8x8_gpio_and_delay_ch32v
    );

    u8x8_InitDisplay(&u8x8);
    u8x8_SetPowerSave(&u8x8, 0);
    u8x8_ClearDisplay(&u8x8);
    u8x8_SetFont(&u8x8, u8x8_font_profont29_2x3_n);

    RingBuffer_Init();

    uint8_t ledState = 0;
    char buffer[16];
    int32_t counter = current_value;
    while (1) {
        GPIO_WriteBit(BLINKY_GPIO_PORT, BLINKY_GPIO_PIN, ledState);
        ledState ^= 1;
        Delay_Ms(1000);
        sprintf(buffer, "%05ld", counter);
        u8x8_DrawString(&u8x8, 3, 1, buffer);
        counter++;
        if (counter >= current_value + 2) {
            RingBuffer_Write(counter);
        }
    }
    return 0;
}

void NMI_Handler(void) {}
void HardFault_Handler(void)
{
    while (1)
    {
    }
}
