#include <renderer/font.hpp>

namespace Game::Renderer {
    Font::Font(const std::string& path, SDL_Renderer* renderer, int ptSize, std::string id)
    : Texture(id), mFont(nullptr), mRenderer(renderer) {
        if (!mRenderer) {
            ERROR("You must specify a renderer!");
            return;
        }
        
        mFont = TTF_OpenFont(path.c_str(), ptSize);
        if (!mFont) {
            ERROR("Error opening font: " << SDL_GetError());
            return;
        }
    }

    Font::Font(const Font& other) 
    : Texture(other) {
        this->mFont = other.mFont;
    }

    Font& Font::operator=(const Font& other) {
        if (this != &other) {
            Texture::operator=(other);
            this->mFont = other.mFont;
        }
        return *this;
    }

    Font::~Font() {
        if (mFont)
            TTF_CloseFont(mFont);
    }

    void Font::build(SDL_Color color, std::string text) {
        if (!mFont) { return; }

        SDL_Surface* surf = TTF_RenderText_Blended(mFont, text.c_str(), text.size(), color);
        if (!surf) {
            ERROR("TTF_RenderText_Blended Error: " << SDL_GetError() << " (This object may be unusuable)");
            return;
        }

        // Convert to texture
        mTex = SDL_CreateTextureFromSurface(mRenderer, surf);
        SDL_DestroySurface(surf);
        if (!mTex) {
            ERROR("SDL_CreateTextureFromSurface Error: " << SDL_GetError() << " (This object may be unusuable)");
            return;
        }
        
    }

    SDL_Texture* Font::getSDLTexture() { return mTex; }
    std::string Font::getId() { return mId; }
}