#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "sg_lgpio.h"
#include "lcd_2inch.h"
#include "lcd_gui.h"
#include "fonts.h"
#include "touch.h"

#define TOOLBAR_WIDTH 60
#define LCD_W_1   320 
#define LCD_H_1   240 
#define BTN_H  40 

#ifndef YELLOW
#define YELLOW  0xFFE0
#endif

u_int16_t *image_buffer;
u_int16_t brush_color = BLACK;
u_int16_t brush_size = 4;     // Brush size in pixels

void Logic_To_Phys(u_int16_t lx, u_int16_t ly, u_int16_t *px, u_int16_t *py) {
    if (ly >= 240) ly = 239;    // Boundary protection
    *px = 240 - ly - 1;
    *py = lx;
}

void Sync_Draw_Brush(u_int16_t lx, u_int16_t ly, u_int16_t color, u_int16_t size) {
    for(int bx = 0; bx < size; bx++) {
        for(int by = 0; by < size; by++) {
            Gui_set_pix(lx + bx, ly + by, color);
        }
    }
    
    // Boundary checking
    int max_lx = lx + size - 1;
    if (max_lx >= LCD_W_1) max_lx = LCD_W_1 - 1; 
    int max_ly = ly + size - 1;
    if (max_ly >= LCD_H_1) max_ly = LCD_H_1 - 1; 
    
    int actual_w = max_lx - lx + 1;
    int actual_h = max_ly - ly + 1;
     
    // Convert to physical coordinates for hardware write
    u_int16_t px_start = 240 - max_ly - 1;
    u_int16_t py_start = lx;
    
    LCD_Write_Block(px_start, py_start, actual_h, actual_w, color);
}

void Fast_Draw_Brush(u_int16_t x, u_int16_t y, u_int16_t color, u_int16_t size) {
    u_int16_t px, py;
    u_int16_t phys_w, phys_h;

    // Convert center point coordinates
    Logic_To_Phys(x, y, &px, &py);

    int start_x = px; 
    int start_y = py; 

    if (px + size >= 240) size = 240 - px;
    if (py + size >= 320) size = 320 - py;

    LCD_Write_Block(px, py, size, size, color);
}

void Draw_Button(int index, u_int16_t bg_color, const char* text, u_int16_t text_color) {
    u_int16_t x_start = 2;
    u_int16_t y_start = index * BTN_H + 2;
    u_int16_t x_end   = TOOLBAR_WIDTH - 2;
    u_int16_t y_end   = (index + 1) * BTN_H - 2;

    Gui_draw_rectangle(x_start, y_start, x_end, y_end, bg_color, 1, FULL);

    if (brush_color == bg_color && (text == NULL || strcmp(text, "CLR") != 0)) {
        u_int16_t border = (bg_color == WHITE) ? RED : WHITE;
        Gui_draw_rectangle(x_start + 2, y_start + 2, x_end - 2, y_end - 2, border, 2, EMPTY);
    }
    if (text != NULL && strlen(text) > 0) {
        Gui_draw_str(x_start + 5, y_start + 12, text, &Font24, text_color, bg_color);
    }
}

void Draw_Toolbar() {
    Gui_draw_line(TOOLBAR_WIDTH, 0, TOOLBAR_WIDTH, LCD_H_1, BLACK, 2, SOLID);
    Draw_Button(0, WHITE, "CLR", BLACK);
    Draw_Button(1, RED, NULL, WHITE);
    Draw_Button(2, GREEN, NULL, WHITE);
    Draw_Button(3, BLUE, NULL, WHITE);
    Draw_Button(4, BLACK, NULL, WHITE);
    Draw_Button(5, YELLOW, NULL, BLACK);
}

int Handle_Toolbar_Click(u_int16_t y) {
    u_int16_t old_color = brush_color;
    int btn_index = y / BTN_H;
    switch (btn_index) {
        case 0: Gui_Clear(WHITE); return 2;    // Full screen clear
        case 1: brush_color = RED; break;
        case 2: brush_color = GREEN; break;
        case 3: brush_color = BLUE; break;
        case 4: brush_color = BLACK; break;
        case 5: brush_color = YELLOW; break;
        default: return 0;
    }
    if (brush_color != old_color) return 1;    // Only refresh toolbar
    return 0;
}


int main(void)
{
    TouchPoint tPoint;
    int is_drawing = 0;
    u_int16_t last_x = 0;
    u_int16_t last_y = 0;
    u_int16_t px, py; 

    image_buffer = (u_int16_t *)malloc(LCD_SIZE);
    if(image_buffer == NULL) return -1;

    Image_Init(image_buffer, LCD_W, LCD_H, ROTATE_90, MIRROR_NONE);
    Lgpio_export();
    Lcd_Init();
    Touch_Init();

    Gui_Clear(WHITE);
	Gui_draw_point(20, 200, YELLOW, 18);
	Gui_draw_line(310, 175, 180, 190, BLUE, 1, SOLID);
	Gui_draw_line(310, 110, 230, 10, BLUE, 2, DOTTED);
	Gui_draw_line(180, 195, 310, 215, RED, 2, DOTTED);
	Gui_draw_rectangle(200, 210, 230, 235, BLUE, 1, EMPTY);
	Gui_draw_rectangle(50, 200, 70, 230, YELLOW, 1, FULL);
	Gui_draw_circle(110, 210, 20, RED,1, EMPTY);
	Gui_draw_circle(170, 220, 15, RED,1, FULL);
	Gui_draw_str(10, 30, "876543210!", &Font24, BLACK, WHITE);
	Gui_draw_str(10, 80, "seengreat!", &Font24, BLUE, WHITE);
	Gui_draw_str(10, 120, "SEENGREAT!", &Font24, GREEN, WHITE);
	Display(Image.img);
	delay(3000);
	
	Gui_Clear(WHITE);	
	Gui_show_bmp("./fruits8.bmp");
	Display(Image.img);
    delay(3000);
    
    Gui_Clear(WHITE);
    Draw_Toolbar();
    Display(image_buffer); 

    printf("Paint App Ready (Fast Mode).\n");

    while(1)
    {
        if(Touch_Read_Point(&tPoint))
        {

            if (tPoint.x < TOOLBAR_WIDTH) {
                is_drawing = 0;
                int status = Handle_Toolbar_Click(tPoint.y);
                if (status == 1 || status == 2) {
                    Draw_Toolbar();
                    Display(image_buffer); 
                    delay(status == 2 ? 200 : 50); 
                }
            } 
           else {
              Sync_Draw_Brush(tPoint.x, tPoint.y, brush_color,brush_size);
            }
        }

    }

    free(image_buffer);
    return 0;
}
