#include <AtomicDataStore/AtomicDataStore.hpp>
#include <DevCommand/WImportDirCommand/WImportDirCommand.hpp>
#include <Log/Log.hpp>
#include <filesystem>
#include <fstream>

int WImportDirCommand::execute(const std::vector<std::string> &args)
{
    if (args.size() != 4)
    {
        Log::error("Syntax: wimportdir <world-file> <directory>");
    }

    std::string worldFile = args[2];
    std::string dir = args[3];

    AtomicDataStore store;
    store.open(worldFile);
    const std::string &error = store.getError();

    if (error.size() != 0)
    {
        Log::error(error);
        return 1;
    }

    AtomicDataStore::Plan plan;
    for (const auto &entry : std::filesystem::recursive_directory_iterator(dir))
    {
        if (!entry.is_regular_file())
        {
            continue;
        }

        std::string name = std::filesystem::relative(entry.path(), dir).string();

        Log::info(formatString("Importing $+...", name));
        std::vector<uint8_t> &content = plan[name];

        std::ifstream ifs(entry.path(), std::ios::binary);

        ifs.seekg(0, std::ios_base::end);
        size_t size = (size_t) ifs.tellg();
        ifs.seekg(0, std::ios_base::beg);

        content.resize(size);
        ifs.read((char*) content.data(), size);

        if (!ifs.good())
        {
            Log::error(formatString("Error while reading $+", name));
            return 1;
        }

        ifs.close();
    }

    Log::info("Committing the plan...");
    store.update(plan, 0);

    Log::info("Import completed.");
    return 0;
}