#include "lcd.h"

#ifdef LCD_ENABLE
#include "jlx12864.h"

static uint32_t utf8_strlen(const char *str)
{
    uint32_t len = 0;

    while (*str) {
        len += (*str++ & 0xc0) != 0x80;
    }
    return len;
}

void LCD_Init()
{
    init_lcd();
    clear_screen();
}

void LCD_PrintRow(uint8_t row, uint8_t y, char *text)
{
    LCD_PutText(row * FONTSIZE_X, y, FONT_1X, COLOR_BLACK, text);
    LCD_LoadData();
}

void LCD_ClearRow(uint8_t row)
{
    clear_page(row);
}

void LCD_PrintAligned(uint8_t row, align_t align, char *text)
{
    uint8_t x = 0;

    switch (align) {
        case alignLEFT:
            x = 0;
            break;
        case alignCENTER:
            x = (LCD_WIDTH - FONTSIZE_X * utf8_strlen(text)) / 2;
            break;
        case alignRIGHT:
            x = LCD_WIDTH - FONTSIZE_X * utf8_strlen(text);
            break;
        default:
            break;
    }
    LCD_ClearRow(row);
    LCD_PutText(x, row * FONTSIZE_Y, FONT_1X, COLOR_BLACK, text);
    LCD_LoadData();
}

void LCD_PrintBar(uint8_t row, uint8_t progress)
{
    const uint8_t x1 = 5;
    const uint8_t x2 = LCD_WIDTH - 10;

    const uint8_t y1 = row * FONTSIZE_Y;
    const uint8_t y2 = y1 + FONTSIZE_Y - 1;

    if (progress > 100) progress == 100;
    const uint8_t len = (x2 - x1 - 3) * progress / 100;

    LCD_ClearRow(row);

    LCD_DrawLine(x1, y1, x2, y1, COLOR_BLACK);
    LCD_DrawLine(x1, y2, x2, y2, COLOR_BLACK);

    LCD_DrawLine(x1, y1, x1, y2, COLOR_BLACK);
    LCD_DrawLine(x2, y1, x2, y2, COLOR_BLACK);

    LCD_FillRegion(x1 + 2, y1 + 2, len, 4, COLOR_BLACK);
    LCD_LoadData();
}
#endif /* LCD_ENABLE */