#include "asset.h"

// Constructor
Asset::Asset(std::string path)
{
    mExecutablePath = path;
}

// Destructor
Asset::~Asset()
{
}

// Añade un elemento a la lista
void Asset::add(std::string file, enum assetType type, bool required)
{
    item_t temp;
    temp.file = mExecutablePath + "/.." + file;
    temp.type = type;
    temp.required = required;
    mFileList.push_back(temp);
}

// Devuelve el fichero de un elemento de la lista a partir de una cadena
std::string Asset::get(std::string text)
{
    for (int i = 0; i < mFileList.size(); i++)
        if (mFileList[i].file.find(text) != std::string::npos)
            return mFileList[i].file;

    printf("Warning: file %s not found\n", text.c_str());
    return "";
}

// Comprueba que existen todos los elementos
bool Asset::check()
{
    bool success = true;

    // Comprueba la lista de ficheros clasificandolos por tipo
    for (int type = 0; type < maxAssetType; type++)
    {
        printf("\n>> %s FILES\n", getTypeName(type).c_str());

        for (int i = 0; i < mFileList.size(); i++)
            if ((mFileList[i].required) && (mFileList[i].type == type))
                success &= checkFile(mFileList[i].file);
    }

    // Resultado
    if (success)
        printf("\n** All files OK.\n\n");
    else
        printf("\n** A file is missing. Exiting.\n\n");

    return success;
}

// Comprueba que existe un fichero
bool Asset::checkFile(std::string path)
{
    bool success = true;

    // Comprueba si existe el fichero
    const std::string filename = path.substr(path.find_last_of("\\/") + 1);
    SDL_RWops *file = SDL_RWFromFile(path.c_str(), "r+b");

    if (file != NULL)
    {
        printf("Checking file %-20s [OK]\n", filename.c_str());
        SDL_RWclose(file);
    }
    else
    {
        printf("Checking file %-20s [ERROR]\n", filename.c_str());
        success = false;
    }

    return success;
}

// Devuelve el nombre del tipo de recurso
std::string Asset::getTypeName(int type)
{
    switch (type)
    {
    case bitmap:
        return "BITMAP";
        break;
    case music:
        return "MUSIC";
        break;
    case sound:
        return "SOUND";
        break;
    case font:
        return "FONT";
        break;
    case lang:
        return "LANG";
        break;
    case data:
        return "DATA";
        break;
    case room:
        return "ROOM";
        break;
    case enemy:
        return "ENEMY";
        break;
    case item:
        return "ITEM";
        break;
    default:
        return "ERROR";
        break;
    }
}