#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 "font.h"

SDL_Color FONT_FontColor;
TTF_Font * FONT_FontFamily = NULL;

void FONT_Initialize(){
    printf("Initializing Font...\n");
    FONT_FontColor = (SDL_Color) {255, 255, 255 };
    FONT_FontFamily = TTF_OpenFont(FONT_FontFile, 48);
    if (!FONT_FontFamily) printf("Font could not initialize! Error: %s\n", TTF_GetError());
    else printf("Font was successfully initialized!\n");
    FONT_PrintFontStyle(FONT_FontFamily);
    printf("Font initialized!\n");
}

void FONT_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 FONT_Deinitialize(){
    printf("De-initializing Font...\n");
    TTF_CloseFont(FONT_FontFamily);
    FONT_FontFamily = NULL; // to be safe...
    printf("Font de-initialized!\n");
}

void FONT_RenderText(SDL_Renderer * renderer, char * text, SDL_Rect * dstRect){
    SDL_Rect srcRect;

    srcRect.x = 0;
    srcRect.y = 0;
    SDL_Texture * texture = FONT_GenerateTexture(renderer, text, &srcRect);
    SDL_RenderCopy(renderer, texture, &srcRect, dstRect);
    SDL_DestroyTexture(texture);
}

SDL_Texture * FONT_GenerateTexture(SDL_Renderer * renderer, char * text, SDL_Rect * Message_rect){
    SDL_Surface * tmpSurface = FONT_GenerateSurface(text, Message_rect);
    SDL_Texture * resultTexture = SDL_CreateTextureFromSurface(renderer, tmpSurface);

    SDL_FreeSurface(tmpSurface);
    return resultTexture;
} /* FONT_GenerateSurface */

SDL_Surface * FONT_GenerateSurface(char * text, SDL_Rect * Message_rect){
    TTF_SizeText(FONT_FontFamily, text, &(Message_rect->w), &(Message_rect->h));
    return TTF_RenderText_Solid(FONT_FontFamily, text, FONT_FontColor);
}
