#include <stdint.h>
#include "monoimg.h"
#include "st7735.h"

#define max(a,b) ((a) >= (b) ? (a) : (b))
#define min(a,b) ((a) <= (b) ? (a) : (b))

uint8_t mimg_get_pixel_unsafe(const uint8_t *img, uint8_t x, uint8_t y) {
    // MVLSB format
    uint8_t width = img[0] + 1;
    uint16_t index = (y >> 3) * width + x + 2;
    uint8_t offset = y & 0x07;
    uint8_t value = (img[index] >> offset) & 0x01;
    return value; // return 1 or 0
}

uint8_t mimg_get_pixel(const uint8_t *img, uint16_t x, uint16_t y) {
    // MVLSB format
    uint8_t width = img[0] + 1;
    uint8_t height = img[1] + 1;
    if (x >= width || y >= height) {
        return 0;
    }
    return mimg_get_pixel_unsafe(img, (uint8_t)x, (uint8_t)y);
}

void mimg_draw(uint16_t x, uint16_t y, uint16_t color, const uint8_t *img, mimg_Area area) {
    uint8_t width_s1 = img[0]; // width - 1
    uint8_t height_s1 = img[1]; // height - 1
    uint8_t ix = min(area.x, width_s1);
    uint8_t iy = min(area.y, height_s1);
    uint8_t iw = min(area.w, width_s1 - ix + 1);
    uint8_t ih = min(area.h, height_s1 - iy + 1);
    uint8_t off_x, off_y;
    for (off_y = 0; off_y < ih; off_y ++) {
        for (off_x = 0; off_x < iw; off_x ++) {
            if (mimg_get_pixel_unsafe(img, ix + off_x, iy + off_y)) {
                ST7735_DrawPixel(x + off_x, y + off_y, color);
            }
        }
    }
}

void mimg_draw_with_bg(uint16_t x, uint16_t y, uint16_t color, uint16_t bg_color, const uint8_t *img, mimg_Area area) {
    uint8_t width_s1 = img[0]; // width - 1
    uint8_t height_s1 = img[1]; // height - 1
    uint8_t ix = min(area.x, width_s1);
    uint8_t iy = min(area.y, height_s1);
    uint8_t iw = min(area.w, width_s1 - ix + 1);
    uint8_t ih = min(area.h, height_s1 - iy + 1);
    uint8_t off_x, off_y;
    ST7735_Select();
    ST7735_SetAddressWindow(x, y, x + iw - 1, y + ih - 1);
    ST7735_WriteCommand(ST7735_RAMWR);
    HAL_GPIO_WritePin(ST7735_DC_GPIO_Port, ST7735_DC_Pin, GPIO_PIN_SET);
    uint8_t data_color[] = {color >> 8, color & 0xFF};
    uint8_t data_bg_color[] = {bg_color >> 8, bg_color & 0xFF};
    for (off_y = 0; off_y < ih; off_y ++) {
        for (off_x = 0; off_x < iw; off_x ++) {
            if (mimg_get_pixel_unsafe(img, ix + off_x, iy + off_y)) {
                HAL_SPI_Transmit(&ST7735_SPI_PORT, data_color, sizeof(data_color), HAL_MAX_DELAY);
            } else {
                HAL_SPI_Transmit(&ST7735_SPI_PORT, data_bg_color, sizeof(data_bg_color), HAL_MAX_DELAY);
            }
        }
    }
    ST7735_Unselect();
}

mimg_Area mimg_get_tile_area(const uint8_t *img, uint8_t cols, uint8_t rows, uint8_t index) {
    uint8_t width = img[0] + 1;
    uint8_t height = img[1] + 1;
    mimg_Area area;
    area.w = width / cols;
    area.h = height / rows;
    area.y = (index / cols) * area.h;
    area.x = (index % cols) * area.w;
    return area;
}
