#include "AssetManager.h"
#include <cstdio>

AssetManager::AssetManager(SDL_Renderer* r) : renderer(r) {}

AssetManager::~AssetManager() {
    for (auto& [_, tex] : textures)
        SDL_DestroyTexture(tex);
    if (font) TTF_CloseFont(font);
    if (bgm) { Mix_HaltMusic(); Mix_FreeMusic(bgm); }
}

SDL_Texture* AssetManager::getTexture(const std::string& path) {
    auto it = textures.find(path);
    if (it != textures.end())
        return it->second;

    SDL_Surface* surf = IMG_Load(path.c_str());
    if (!surf) {
        fprintf(stderr, "IMG_Load error: %s - %s\n", path.c_str(), IMG_GetError());
        return nullptr;
    }
    SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf);
    SDL_FreeSurface(surf);
    if (tex) {
        SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
    } else {
        fprintf(stderr, "CreateTexture error: %s - %s\n", path.c_str(), SDL_GetError());
        return nullptr;
    }
    textures[path] = tex;
    return tex;
}

bool AssetManager::loadFont(const char* path, int size) {
    font = TTF_OpenFont(path, size);
    if (font) {
        printf("Loaded font: %s\n", path);
        return true;
    }
    return false;
}

bool AssetManager::loadBGM(const char* path) {
    bgm = Mix_LoadMUS(path);
    if (bgm) {
        Mix_PlayMusic(bgm, -1);
        return true;
    }
    fprintf(stderr, "BGM load failed: %s\n", Mix_GetError());
    return false;
}
