#include "manage_hiscore_table.h"
#include <SDL2/SDL_error.h> // Para SDL_GetError
#include <SDL2/SDL_rwops.h> // Para SDL_RWread, SDL_RWwrite, SDL_RWFromFile
#include <algorithm>        // Para sort
#include <iostream>         // Para basic_ostream, operator<<, cout, endl
#include "utils.h"          // Para HiScoreEntry, getFileName

// Resetea la tabla a los valores por defecto
void ManageHiScoreTable::clear()
{
    // Limpia la tabla
    table_.clear();

    // Añade 10 entradas predefinidas
    table_.push_back(HiScoreEntry("Bry", 1000000));
    table_.push_back(HiScoreEntry("Usufondo", 500000));
    table_.push_back(HiScoreEntry("G.Lucas", 100000));
    table_.push_back(HiScoreEntry("P.Delgat", 50000));
    table_.push_back(HiScoreEntry("P.Arrabalera", 10000));
    table_.push_back(HiScoreEntry("Pelechano", 5000));
    table_.push_back(HiScoreEntry("Sahuquillo", 1000));
    table_.push_back(HiScoreEntry("Bacteriol", 500));
    table_.push_back(HiScoreEntry("Pepe", 200));
    table_.push_back(HiScoreEntry("Rosita", 100));
}

// Añade un elemento a la tabla
void ManageHiScoreTable::add(HiScoreEntry entry)
{
    // Añade la entrada a la tabla
    table_.push_back(entry);

    // Ordena la tabla
    sort();

    // Deja solo las 10 primeras entradas
    table_.resize(10);
}

// Ordena la tabla
void ManageHiScoreTable::sort()
{
    struct
    {
        bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
    } scoreDescendingComparator;

    std::sort(table_.begin(), table_.end(), scoreDescendingComparator);
}

// Carga la tabla con los datos de un fichero
bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
{
    clear();
    auto success = true;
    auto file = SDL_RWFromFile(file_path.c_str(), "r+b");

    if (file)
    {
        std::cout << "Reading file: " << getFileName(file_path) << std::endl;

        for (auto &entry : table_)
        {
            int nameSize = 0;

            if (SDL_RWread(file, &entry.score, sizeof(int), 1) == 0)
            {
                success = false;
                break;
            }

            if (SDL_RWread(file, &nameSize, sizeof(int), 1) == 0)
            {
                success = false;
                break;
            }

            std::vector<char> nameBuffer(nameSize + 1);
            if (SDL_RWread(file, nameBuffer.data(), sizeof(char) * nameSize, 1) == 0)
            {
                success = false;
                break;
            }

            nameBuffer[nameSize] = '\0';
            entry.name = std::string(nameBuffer.data());
        }

        SDL_RWclose(file);
    }

    if (!success)
    {
        clear();
    }

    return success;
}

// Guarda la tabla en un fichero
bool ManageHiScoreTable::saveToFile(const std::string &file_path)
{
    auto success = true;
    auto file = SDL_RWFromFile(file_path.c_str(), "w+b");

    if (file)
    {
        // Guarda los datos
        for (int i = 0; i < (int)table_.size(); ++i)
        {
            SDL_RWwrite(file, &table_.at(i).score, sizeof(int), 1);
            const int nameSize = (int)table_.at(i).name.size();
            SDL_RWwrite(file, &nameSize, sizeof(int), 1);
            SDL_RWwrite(file, table_.at(i).name.c_str(), nameSize, 1);
        }

        std::cout << "Writing file: " << getFileName(file_path).c_str() << std::endl;
        SDL_RWclose(file);
    }
    else
    {
        std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl;
    }
    return success;
}