//
// Created by bruno on 17.2.2025.
//

#include "sevenseg.h"
#include "stdlib.h"

#include <SDL2/SDL_render.h>
#include <stdio.h>

void render_segment(SDL_Renderer *renderer, SevenSegment *display) {
    int seg_width = display->rect->w / 4;
    int seg_height = display->rect->h / 10;

// Define segment positions
    SDL_Rect segments[9] = {
            {seg_width,     display->rect->y, seg_width * 2, seg_height},       // Top
            {3 * seg_width + 4, seg_height,       seg_height,    seg_height * 3.5},            // Top Right
            {3 * seg_width + 4, 5.5 * seg_height, seg_height,    seg_height * 3.5},        // Bottom Right
            {seg_width,     9 * seg_height,   seg_width * 2, seg_height},         // Bottom
            {display->rect->x,  5.5 * seg_height, seg_height,    seg_height * 3.5},     // Bottom Left
            {display->rect->x,  seg_height,       seg_height,    seg_height * 3.5},         // Top Left
            {seg_width,     4.5 * seg_height, seg_width * 2, seg_height},         // Middle
    };

    if (display->value & (1 << 7)) {
        SDL_SetRenderDrawColor(renderer, 0, 64, 64, 255);
    } else {
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    }

    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    for (int i = 0; i < 7; i++) {
        if (display->value & (1 << i)) {
            SDL_RenderFillRect(renderer, &segments[i]);
        }
    }
}

void update_display_texture(SDL_Renderer *renderer, SevenSegment *display) {
    SDL_SetRenderTarget(renderer, display->texture);

    render_segment(renderer, display);

    SDL_SetRenderTarget(renderer, NULL);
}

void init_seven_segment(SevenSegment *display, SDL_Renderer *renderer, int x, int y, int width, int height) {
    display->rect = malloc(sizeof(SDL_Rect));
    display->outRect = malloc(sizeof(SDL_Rect));
    display->value = 0;

    display->rect->x = 0;
    display->rect->y = 0;
    display->rect->w = width;
    display->rect->h = height;

    display->outRect->x = x;
    display->outRect->y = y;
    display->outRect->w = width;
    display->outRect->h = height;

    display->texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
    if (!display->texture) {
        fprintf(stderr, "Failed to create texture: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    update_display_texture(renderer, display);
}

void render_seven_segment(SevenSegment *display, SDL_Renderer *renderer) {
    if (display->oldValue != display->value) {
        display->oldValue = display->value;
        update_display_texture(renderer, display);
    }
    if (display->texture) {
        SDL_RenderCopy(renderer, display->texture, NULL, display->outRect);
    }
}

void destroy_seven_segment(SevenSegment *display) {
    SDL_DestroyTexture(display->texture);
    free(display->rect);
    free(display->outRect);
}