//
// Created by m on 12/3/21.
//

#include "sdltexturemanager.hpp"

SDL_Surface *SdlTextureManager::load_surface(const std::string& path) {
    SDL_Surface* surface = IMG_Load(path.c_str());
    if(surface == nullptr) {
        printf("failed ot load image: %s\n", IMG_GetError());
    }
    return surface;
}

std::shared_ptr<SDL_Texture> SdlTextureManager::load_resource(TextureManagerFetchArgs args) {
    std::string full_path = get_resource_path(args.path);
    SDL_Surface* surface = load_surface(full_path);
    if(surface == nullptr) {
        throw MissingTextureException(full_path, SDL_GetError());
    }
    if(args.color_key.has_value()) {
        Color color_key = args.color_key.value();
        SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, color_key.r, color_key.g, color_key.b));
    }
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer.get(), surface);
    SDL_FreeSurface(surface);
    if(texture == nullptr) {
        throw MissingTextureException(full_path, SDL_GetError());
    }
    return std::shared_ptr<SDL_Texture>(texture, SDL_DestroyTexture);
}

std::string SdlTextureManager::get_key(TextureManagerFetchArgs args) {
    std::string key;
    if(args.color_key.has_value()) {
        key += fmt::format("{}_{}_{}_{}_", args.color_key->r, args.color_key->g, args.color_key->b, args.color_key->a);
    }
    key += fmt::format("{}", args.path);
    return key;
}

std::shared_ptr<SDL_Texture> SdlTextureManager::load_text_as_texture(const std::string& text, const std::shared_ptr<TTF_Font>& font, Color color) {
    SDL_Surface *surface = TTF_RenderText_Solid(font.get(), text.c_str(), {color.r, color.g, color.b});
    if(surface == nullptr) {
        throw MissingTextureException("font", SDL_GetError());
    }
    SDL_Texture *texture = SDL_CreateTextureFromSurface(this->renderer.get(), surface);
    SDL_FreeSurface(surface);
    if(texture == nullptr) {
        throw MissingTextureException("font", SDL_GetError());
    }
    return std::shared_ptr<SDL_Texture>(texture, SDL_DestroyTexture);
}
