#include "ui.h"

void 
render_text(SDL_Renderer* renderer, TTF_Font* font, const char* text, SDL_Rect* rect) {
    SDL_Color color = {200, 200, 200, UI_ALPHA};
    SDL_Surface* surface = TTF_RenderText_Blended(font, text, color);
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    
    SDL_Rect text_rect = {
        rect->x + (rect->w - surface->w) / 2,
        rect->y + (rect->h - surface->h) / 2,
        surface->w,
        surface->h
    };
    
    SDL_RenderCopy(renderer, texture, NULL, &text_rect);
    SDL_FreeSurface(surface);
    SDL_DestroyTexture(texture);
}


void 
init_ui(UI* ui)
{
    ui->zoom_display= (SDL_Rect){UI_PADDING, UI_PADDING, BUTTON_WIDTH, BUTTON_HEIGHT};
    
    ui->fps_display = (SDL_Rect){UI_PADDING, UI_PADDING * 2 + BUTTON_HEIGHT, 
                                        BUTTON_WIDTH, BUTTON_HEIGHT};
    TTF_Init();

    //ui->font = TTF_OpenFont("/System/Library/Fonts/Monaco.ttf", FONT_SIZE);
    //ui->font = TTF_OpenFont("C:/Windows/Fonts/arial.ttf", FONT_SIZE);
    ui->font = TTF_OpenFont("/usr/share/fonts/nerdfonts/TerminessNerdFont-Regular.ttf", FONT_SIZE);
    if (!ui->font) {
        printf("Font yüklenemedi: %s\n", TTF_GetError());
    }
}

void 
render_ui(UI* ui, SDL_Renderer* renderer, ViewInfo view, float fps)
{
    SDL_SetRenderDrawColor(renderer, 60, 60, 60, UI_ALPHA);
    SDL_RenderFillRect(renderer, &ui->zoom_display);
    SDL_RenderFillRect(renderer, &ui->fps_display);
    
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, UI_ALPHA);
    SDL_RenderDrawRect(renderer, &ui->zoom_display);
    SDL_RenderDrawRect(renderer, &ui->fps_display);

    if (ui->font) {
        char buf[16];
        snprintf(buf, sizeof(buf), "Zoom %.3gx", view.zoom);
        render_text(renderer, ui->font, buf, &ui->zoom_display);

        snprintf(buf, sizeof(buf), "Fps %.2f", fps);
        render_text(renderer, ui->font, buf, &ui->fps_display);
    }
}

void cleanup_ui(UI* ui)
{
    if (ui->font) {
        TTF_CloseFont(ui->font);
    }
    TTF_Quit();

}
