#include "resource.h"
#include <iostream>         // Para basic_ostream, operator<<, cout, endl
#include "animatedsprite.h" // Para animatedSprite_t, loadAnimationFromFile
#include "asset.h"          // Para Asset
#include "enemy.h"          // Para enemy_t
#include "item.h"           // Para item_t
#include "room.h"           // Para room_t, loadRoomFile, loadRoomTileFile
#include "text.h"           // Para textFile_t, LoadTextFile
#include "texture.h"        // Para Texture
#include "utils.h"          // Para options_t
#include "screen.h"
#include "options.h"

// [SINGLETON]
Resource *Resource::resource_ = nullptr;

// [SINGLETON] Crearemos el objeto con esta función estática
void Resource::init()
{
    Resource::resource_ = new Resource();
}

// [SINGLETON] Destruiremos el objeto con esta función estática
void Resource::destroy()
{
    delete Resource::resource_;
}

// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
Resource *Resource::get()
{
    return Resource::resource_;
}

// Carga las texturas de una lista
void Resource::loadTextures(std::vector<std::string> list)
{
    for (auto l : list)
    {
        if (options.console)
        {
            std::cout << "\nLOAD TEXTURE: " << l << std::endl;
            std::cout << "png: " << Asset::get()->get(l) << std::endl;
        }

        res_texture_t t;
        t.name = l;
        t.texture = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options.console);
        textures_.push_back(t);
    }
}

// Vuelve a cargar las texturas
void Resource::reLoadTextures()
{
    for (auto texture : textures_)
    {
        texture.texture->reLoad();
    }
}

// Carga las animaciones desde una lista
void Resource::loadAnimations(std::vector<std::string> list)
{
    for (auto l : list)
    {
        // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
        const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png";

        if (options.console)
        {
            std::cout << "\nLOAD ANIMATION: " << l << std::endl;
            std::cout << "png: " << Asset::get()->get(pngFile) << std::endl;
            std::cout << "ani: " << Asset::get()->get(l) << std::endl;
        }

        res_animation_t as;
        as.name = l;
        as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options.console));
        animations_.push_back(as);
    }
}

// Vuelve a cargar las animaciones
void Resource::reLoadAnimations()
{
    // reLoadTextures();

    for (auto &a : animations_)
    {
        // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura
        const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png";
        delete a.animation;
        a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options.console));
    }
}

// Carga los offsets desde una lista
void Resource::loadOffsets(std::vector<std::string> list)
{
    for (auto l : list)
    {
        res_textOffset_t to;
        to.name = l;
        to.textFile = new textFile_t(LoadTextFile(Asset::get()->get(l), options.console));
        offsets_.push_back(to);
    }
}

// Vuelve a cargar los offsets
void Resource::reLoadOffsets()
{
    for (auto &o : offsets_)
    {
        delete o.textFile;
        o.textFile = new textFile_t(LoadTextFile(Asset::get()->get(o.name), options.console));
    }
}

// Carga los mapas de tiles desde una lista
void Resource::loadTileMaps(std::vector<std::string> list)
{
    for (auto l : list)
    {
        res_tileMap_t tm;
        tm.name = l;
        tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options.console));
        tile_maps_.push_back(tm);
    }
}

// Vuelve a cargar los mapas de tiles
void Resource::reLoadTileMaps()
{
    for (auto &tm : tile_maps_)
    {
        delete tm.tileMap;
        tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options.console));
    }
}

// Carga las habitaciones desde una lista
void Resource::loadRooms(std::vector<std::string> list)
{
    for (auto l : list)
    {
        res_room_t r;
        r.name = l;
        r.room = new room_t(loadRoomFile(Asset::get()->get(l), options.console));
        r.room->tileMap = getTileMap(r.room->tileMapFile);
        for (auto &e : r.room->enemies)
        {
            e.animation = getAnimation(e.animationString);
        }
        for (auto &i : r.room->items)
        {
            i.texture = getTexture(i.tileSetFile);
        }
        r.room->textureA = getTexture("standard.png");
        r.room->textureB = getTexture("standard_zxarne.png");
        rooms_.push_back(r);
    }
}

// Vuelve a cargar las habitaciones
void Resource::reLoadRooms()
{
    reLoadTileMaps();

    for (auto &r : rooms_)
    {
        delete r.room;
        r.room = new room_t(loadRoomFile(Asset::get()->get(r.name)));
        r.room->tileMap = getTileMap(r.room->tileMapFile);
        for (auto &e : r.room->enemies)
        {
            e.animation = getAnimation(e.animationString);
        }
        for (auto &i : r.room->items)
        {
            i.texture = getTexture(i.tileSetFile);
        }
        r.room->textureA = getTexture("standard.png");
        r.room->textureB = getTexture("standard_zxarne.png");
    }
}

// Vuelve a cargar todos los recursos
void Resource::reLoad()
{
    reLoadAnimations();
    reLoadOffsets();
    reLoadRooms();
}

// Libera las texturas
void Resource::freeTextures()
{
    for (auto texture : textures_)
    {
        delete texture.texture;
    }
    textures_.clear();
}

// Libera las animaciones
void Resource::freeAnimations()
{
    for (auto a : animations_)
    {
        delete a.animation;
    }
    animations_.clear();
}

// Libera los offsets
void Resource::freeOffsets()
{
    for (auto o : offsets_)
    {
        delete o.textFile;
    }
    offsets_.clear();
}

// Libera los mapas de tiles
void Resource::freeTileMaps()
{
    for (auto t : tile_maps_)
    {
        delete t.tileMap;
    }
    tile_maps_.clear();
}

// Libera las habitaciones
void Resource::freeRooms()
{
    for (auto r : rooms_)
    {
        delete r.room;
    }
    rooms_.clear();
}

// Libera todos los recursos
void Resource::free()
{
    freeTextures();
    freeAnimations();
    freeOffsets();
    freeTileMaps();
    freeRooms();
}

// Obtiene una textura
Texture *Resource::getTexture(std::string name)
{
    for (auto texture : textures_)
    {
        // if (texture.name.find(name) != std::string::npos)
        if (texture.name == name)
        {
            // std::cout << "\nTEXTURE REQUESTED: " << name << std::endl;
            // std::cout << "served: " << texture.name << std::endl;

            return texture.texture;
        }
    }

    if (options.console)
    {
        std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
    }
    return nullptr;
}

// Obtiene una animación
animatedSprite_t *Resource::getAnimation(std::string name)
{
    for (auto animation : animations_)
    {
        // if (animation.name.find(name) != std::string::npos)
        if (animation.name == name)
        {
            // std::cout << "\nANIMATION REQUESTED: " << name << std::endl;
            // std::cout << "served: " << animation.name << std::endl;
            return animation.animation;
        }
    }

    if (options.console)
    {
        std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
    }
    return nullptr;
}

// Obtiene un offset
textFile_t *Resource::getOffset(std::string name)
{
    for (auto offset : offsets_)
    {
        // if (offset.name.find(name) != std::string::npos)
        if (offset.name == name)
        {
            return offset.textFile;
        }
    }

    if (options.console)
    {
        std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
    }
    return nullptr;
}

// Obtiene un mapa de tiles
std::vector<int> *Resource::getTileMap(std::string name)
{
    for (auto tileMap : tile_maps_)
    {
        // if (tileMap.name.find(name) != std::string::npos)
        if (tileMap.name == name)
        {
            return tileMap.tileMap;
        }
    }

    if (options.console)
    {
        std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
    }
    return nullptr;
}

// Obtiene una habitacion
room_t *Resource::getRoom(std::string name)
{
    for (auto room : rooms_)
    {
        // if (room.name.find(name) != std::string::npos)
        if (room.name == name)
        {
            return room.room;
        }
    }

    if (options.console)
    {
        std::cout << "NOT FOUND ON CACHE: " << name << std::endl;
    }
    return nullptr;
}

// Obtiene todas las habitaciones
std::vector<res_room_t> *Resource::getAllRooms()
{
    return &rooms_;
}