#include "../include/utils.h"



size_t image_size_profile(int profile, int width, int height)
{
    size_t size = sizeof(bopti_image_t);

    if(profile == 0 || profile == 1) // PX_RGB565, PX_RGB565A
        size += width * height * 2;
    else if(profile == 2) // PX_P8
        size += 512 + width * height;
    else if(profile == 3) // PX_P4
        size += 32 + ((width + 1) / 2) * height;

    return size;
}

size_t image_size(bopti_image_t const *img)
{
    return image_size_profile(img->profile, img->width, img->height);
}

int get_pixel(bopti_image_t const *img, int x, int y)
{
    if((unsigned)x >= img->width || (unsigned)y >= img->height)
        return 0;

    uint8_t *bytes = (void *)img->data;

    if(img->profile <= 1)
        return img->data[y * img->width + x];
    if(img->profile == 2)
        return bytes[y * img->width + x + 512];
    if(img->profile == 3)
    {
        int s = (img->width + 1) >> 1;
        int i = y * s + (x >> 1) + 32;
        if(x & 1)
            return bytes[i] & 0x0f;
        else
            return bytes[i] >> 4;
    }
    return 0;
}

void set_pixel(bopti_image_t *img, int x, int y, int color)
{
    if((unsigned)x >= img->width || (unsigned)y >= img->height)
        return;

    uint8_t *bytes = (void *)img->data;

    if(img->profile <= 1)
        img->data[y * img->width + x] = color;
    else if(img->profile == 2)
        bytes[y * img->width + x + 512] = color;
    else if(img->profile == 3)
    {
        int s = (img->width + 1) >> 1;
        int i = y * s + (x >> 1) + 32;
        if(x & 1)
            bytes[i] = (bytes[i] & 0xf0) | (color & 0x0f);
        else
            bytes[i] = (bytes[i] & 0x0f) | ((color & 0x0f) << 4);
    }
}

bopti_image_t *resize(bopti_image_t const *src, int w, int h)
{
    size_t size = image_size_profile(src->profile, w, h);
    bopti_image_t *img = malloc(size);
    if(!img) return NULL;

    size_t palette_size = 0;
    if(src->profile == 2) // PX_P8
        palette_size = 512;
    else if(src->profile == 3) // PX_P4
        palette_size = 32;

    img->profile = src->profile;
    img->alpha = src->alpha;
    img->width = w;
    img->height = h;
    memcpy(img->data, src->data, palette_size);

    for(int y = 0; y < h; y++)
        for(int x = 0; x < w; x++)
        {
            int color = get_pixel(src, x * src->width / w, y * src->height / h);
            set_pixel(img, x, y, color);
        }

    return img;
}

