#include <stdint.h>
#include "ui_utils.h"
#include "st7735.h"
#include "bmfont.h"
#include "asciifont.h"

#define MAX_LINES 16
#define TITLE_COLOR_BG ST7735_COLOR565(0x20, 0x20, 0x20)

const StrItem NULL_STR_ITEM = { NULL, 0 };

void uiu_text_area(bmf_BitmapFont *font, const uint8_t *text, uint32_t len, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t align, uint16_t color, uint16_t bg_color) {
    // calc line width
    uint16_t lws[MAX_LINES];
    uint16_t gws[MAX_LINES];
    uint16_t max_width = 0;
    uint8_t lines = 0;
    uint16_t p_off = 0;
    while ((p_off < len) && ((lines + 1) * font->char_height <= h) && (lines < MAX_LINES)) {
        uint16_t fitlen = bmf_get_text_offset(font, text + p_off, len - p_off, w, font->char_height);
        if (fitlen == 0) {
            break;
        }
        lws[lines] = fitlen;
        gws[lines] = bmf_get_text_width(font, text + p_off, fitlen);
        max_width = (gws[lines] > max_width) ? gws[lines] : max_width;
        lines ++;
        p_off += fitlen;
    }
    // draw lines
    uint16_t off_x = 0;
    uint16_t off_y = 0;
    if (align & uiu_ALIGN_VBOTTOM) {
        off_y = y + (h - (lines * font->char_height));
    }else if (align & uiu_ALIGN_VCENTER) {
        off_y = y + ((h - (lines * font->char_height)) / 2);
    }else {
        off_y = y;
    }
    uint8_t cur_lines;
    p_off = 0;
    ST7735_FillRectangle(x, y, w, h, bg_color);
    for (cur_lines = 0; cur_lines < lines; cur_lines ++) {
        if (align & uiu_ALIGN_HRIGHT) {
            off_x = x + (w - gws[cur_lines]);
        } else if (align & uiu_ALIGN_HCENTER) {
            off_x = x + ((w - gws[cur_lines]) / 2);
        } else {
            off_x = x;
        }
        bmf_draw_text(font, text + p_off, lws[cur_lines], off_x, off_y, gws[cur_lines], font->char_height, color);
        off_y += font->char_height;
        p_off += lws[cur_lines];
    }
}

void uiu_title(const uint8_t *text, uint32_t len) {
    ST7735_FillRectangle(0, 0, ST7735_WIDTH, 16, TITLE_COLOR_BG);
    uiu_text_area(font_unifont_8x16, text, len, 0, 0, ST7735_WIDTH, 16, uiu_ALIGN_HCENTER | uiu_ALIGN_VCENTER, ST7735_YELLOW, TITLE_COLOR_BG);
}
