#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

#include "highscores.h"

#define HIGHSCORES_FontFile "assets/fonts/monofur.ttf"

int HIGHSCORES_EntriesGot = 0;
User * HIGHSCORES_UserList;
SDL_Color HIGHSCORES_FontColor;
SDL_Texture * HIGHSCORES_TableTexture;
SDL_Rect HIGHSCORES_TotalRect;
TTF_Font * HIGHSCORES_FontFamily = NULL;
SDL_Surface * tempSurface;

void HIGHSCORES_Initialize(){
    printf("Initializing Highscores...\n");
    HIGHSCORES_FontColor = (SDL_Color) {255, 255, 255 };
    HIGHSCORES_UserList = malloc(10 * sizeof(User));
    HIGHSCORES_FontFamily = TTF_OpenFont(HIGHSCORES_FontFile, 48);
    if (!HIGHSCORES_FontFamily) printf("Font could not initialize! Error: %s\n", TTF_GetError());
    else printf("Font was successfully initialized!\n");
    printFontStyle(HIGHSCORES_FontFamily);
    HIGHSCORES_TotalRect = (SDL_Rect) {.x = 0, .y = 0, .w = 1920, .h = 1080 };
    printf("Highscores initialized!\n");
}

void printFontStyle(TTF_Font * ffont){
    int style;

    style = TTF_GetFontStyle(ffont);
    printf("The font style is:");
    if (style == TTF_STYLE_NORMAL)
        printf(" normal");
    else {
        if (style & TTF_STYLE_BOLD)
            printf(" bold");
        if (style & TTF_STYLE_ITALIC)
            printf(" italic");
        if (style & TTF_STYLE_UNDERLINE)
            printf(" underline");
        if (style & TTF_STYLE_STRIKETHROUGH)
            printf(" strikethrough");
    }
    printf("\n");
}

void HIGHSCORES_Draw(SDL_Renderer * renderer){
    SDL_RenderCopy(renderer, HIGHSCORES_TableTexture, &HIGHSCORES_TotalRect, &HIGHSCORES_TotalRect);
} /* HIGHSCORES_Draw */

void HIGHSCORES_Deinitialize(){
    printf("De-initializing Highscores...\n");
    TTF_CloseFont(HIGHSCORES_FontFamily);
    HIGHSCORES_FontFamily = NULL; // to be safe...
    SDL_DestroyTexture(HIGHSCORES_TableTexture);
    SDL_FreeSurface(tempSurface);
    free(HIGHSCORES_UserList);
    printf("Highscores de-initialized!\n");
}

void HIGHSCORES_GenerateTexture(SDL_Renderer * renderer){
    char * buffer = calloc(100, sizeof(char));
    int count = 0;
    char format[20] = "| %-58s | %-10s |";
    SDL_Rect Message_rect;
    SDL_Surface * HIGHSCORES_TableSurface = SDL_CreateRGBSurface(0, 1920, 1080, 32, 0, 0, 0, 0);

    if (!HIGHSCORES_TableSurface) {
        printf("Surface wasn't created!\n");
    }
    sprintf(buffer, format, "Username", "Score");
    HIGHSCORES_DrawText(buffer, &Message_rect);
    Message_rect.y = 70;
    Message_rect.x = 50;
    Message_rect.h = 50;
    Message_rect.w = 50;
    SDL_BlitSurface(tempSurface, NULL, HIGHSCORES_TableSurface, &Message_rect);
    SDL_FreeSurface(tempSurface);
    while (count < HIGHSCORES_EntriesGot) {
        sprintf(buffer, format, HIGHSCORES_UserList[count].Username, HIGHSCORES_UserList[count].Score);
        HIGHSCORES_DrawText(buffer, &Message_rect);
        Message_rect.y = ((Message_rect.h + 15) * (count + 1)) + 140;
        Message_rect.x = 50;
        SDL_BlitSurface(tempSurface, NULL, HIGHSCORES_TableSurface, &Message_rect);
        SDL_FreeSurface(tempSurface);
        count++;
    }
    HIGHSCORES_TableTexture = SDL_CreateTextureFromSurface(renderer, HIGHSCORES_TableSurface);
    if (!HIGHSCORES_TableTexture) {
        printf("Texture wasn't created!\n");
    }
    SDL_FreeSurface(HIGHSCORES_TableSurface);
} /* HIGHSCORES_GenerateSurface */

void HIGHSCORES_DrawText(char * text, SDL_Rect * Message_rect){
    TTF_SizeText(HIGHSCORES_FontFamily, text, &(Message_rect->w), &(Message_rect->h));
    tempSurface = TTF_RenderText_Solid(HIGHSCORES_FontFamily, text, HIGHSCORES_FontColor);
}

void HIGHSCORES_ReloadList(){
    printf("Call BHI interface:\n");
    system("bhi top output.txt");
    printf("BHI interface quit!\nBHI output handling...\n");

    HIGHSCORES_EntriesGot = 0;
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    char * name, * scorestring;
    int nameCharCount = 0, scoreCharCount = 0;
    bool switchread = false;
    HIGHSCORES_UserList = malloc(10 * sizeof(User));
    fp = fopen("output.txt", "r");
    if (fp == NULL)
        return;
    if ((read = getline(&line, &len, fp)) != -1)
        if (line[0] == 0)
            return;
    int counter = 0;
    while ((read = getline(&line, &len, fp)) != -1) {
        name = malloc(read * sizeof(char));
        scorestring = malloc(read * sizeof(char));
        nameCharCount = 0;
        scoreCharCount = 0;
        switchread = false;
        #ifdef DEBUG
        printf("Retrieved line of length %u:\n", read);
        printf("%s", line);
        #endif
        for (ssize_t i = 0; i < read; i++) {
            if (line[i] == '+') {
                switchread = true;
                continue;
            }
            if (switchread) {
                if (line[i] == '\n') break;
                scorestring[scoreCharCount++] = line[i];
            } else
                name[nameCharCount++] = line[i];
        }
        name[nameCharCount] = '\0';
        scorestring[scoreCharCount] = '\0';
        User tmp;
        strcpy(tmp.Username, name);
        strcpy(tmp.Score, scorestring);
        HIGHSCORES_UserList[counter++] = tmp;
    }
    free(name);
    free(scorestring);

    fclose(fp);
    if (line)
        free(line);
    for (size_t i = 0; i < counter; i++) {
        printf("User: %s -> Score: %s\n", HIGHSCORES_UserList[i].Username, HIGHSCORES_UserList[i].Score);
    }

    HIGHSCORES_EntriesGot = counter;
    printf("BHI Interface successfully quit!\n");
} /* main */
