#include "ConfigLoader.h"

#include <string>
#include <utility>

#include "toml.hpp"

#include "TomlHelpers.h"

UnlocksConfig ConfigLoader::loadUnlocks(const std::string& path)
{
    const std::string file = "unlocks.toml";
    toml::table tbl = utility::parseFile(path, file);

    UnlocksConfig cfg;
    if (!tbl.contains("unlock"))
    {
        return cfg;
    }

    const toml::array& arr = utility::requireArray(tbl["unlock"], file, "unlock");

    for (std::size_t i = 0; i < arr.size(); ++i)
    {
        const std::string elemPath = "unlock[" + std::to_string(i) + "]";
        const toml::table* ut = arr[i].as_table();
        if (ut == nullptr)
        {
            throw utility::makeError(file, elemPath, "not a table");
        }
        toml::table& mt = const_cast<toml::table&>(*ut);

        UnlockGroupDef def;
        def.id           = utility::requireString(mt["id"], file, elemPath + ".id");
        def.stationLevel = static_cast<int>(
            utility::requireInt(mt["station_level"], file, elemPath + ".station_level"));
        if (mt.contains("requires"))
        {
            def.requiredGroupIds = utility::requireStringArray(mt["requires"], file, elemPath + ".requires");
        }
        if (mt.contains("ships"))
        {
            def.ships = utility::requireStringArray(mt["ships"], file, elemPath + ".ships");
        }
        if (mt.contains("modules"))
        {
            def.modules = utility::requireStringArray(mt["modules"], file, elemPath + ".modules");
        }
        if (mt.contains("buildings"))
        {
            def.buildings = utility::requireStringArray(mt["buildings"], file, elemPath + ".buildings");
        }
        if (mt.contains("recipes"))
        {
            def.recipes = utility::requireStringArray(mt["recipes"], file, elemPath + ".recipes");
        }

        cfg.groups.push_back(std::move(def));
    }

    return cfg;
}
