#include "main.h"
#include "display.h"

__attribute__((section(".sdram")))
volatile pixel_t framebuffer1[DISPLAY_HEIGHT * DISPLAY_WIDTH];
volatile pixel_t framebuffer2[DISPLAY_HEIGHT * DISPLAY_WIDTH];

volatile pixel_t *current_framebuffer = framebuffer1;
volatile pixel_t *next_framebuffer = framebuffer2;

extern LTDC_HandleTypeDef hltdc;
extern DMA2D_HandleTypeDef hdma2d;

void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef *hltdc)
{
    // Swap the LTDC's active framebuffer address to the back buffer
    HAL_LTDC_SetAddress(hltdc, (uint32_t)current_framebuffer, 0);

    // Clear the Line Interrupt pending bit
    HAL_NVIC_DisableIRQ(LTDC_IRQn);
}

void copy_current_to_next_framebuffer(void)
{
    for (uint32_t i = 0; i < DISPLAY_HEIGHT * DISPLAY_WIDTH; i++)
    {
        next_framebuffer[i] = current_framebuffer[i];
    }
}

void swap_framebuffers(void)
{
    volatile pixel_t *temp = current_framebuffer;
    current_framebuffer = next_framebuffer;
    next_framebuffer = temp;
    HAL_LTDC_ProgramLineEvent(&hltdc, 296);
    HAL_NVIC_EnableIRQ(LTDC_IRQn);
    
    copy_current_to_next_framebuffer();
}