#include "JsonUtils.h"

#include <Console.h>
#include <Datei.h>

#include "Game.h"

int countAllJsonsInDirectory(Framework::Text path)
{
    int count = 0;
    if (path.hatAt(path.getLength() - 1, "/")
        || path.hatAt(path.getLength() - 1, "\\"))
    {
        path.remove(path.getLength() - 1, path.getLength());
    }
    Framework::Datei dir(path);
    if (dir.istOrdner())
    {
        Framework::RCArray<Framework::Text>* list = dir.getDateiListe();
        for (Framework::Text* name : *list)
        {
            Framework::Text nextPath = path + "/" + *name;
            count += countAllJsonsInDirectory(nextPath);
        }
        list->release();
    }
    else if (path.hatAt(path.getLength() - 5, ".json") && dir.existiert())
    {
        count++;
    }
    return count;
}

void internalLoadAllJsonsFromDirectory(Framework::Text path,
    std::function<void(
        Framework::JSON::JSONValue* zValue, Framework::Text path)> action,
    Framework::ConsoleProgressBar* progress)
{
    if (path.hatAt(path.getLength() - 1, "/")
        || path.hatAt(path.getLength() - 1, "\\"))
    {
        path.remove(path.getLength() - 1, path.getLength());
    }
    Framework::Datei dir(path);
    if (dir.istOrdner())
    {
        Framework::RCArray<Framework::Text>* list = dir.getDateiListe();
        for (Framework::Text* name : *list)
        {
            Framework::Text nextPath = path + "/" + *name;
            internalLoadAllJsonsFromDirectory(nextPath, action, progress);
        }
        list->release();
    }
    else if (path.hatAt(path.getLength() - 5, ".json") && dir.existiert())
    {
        Framework::JSON::JSONValue* value
            = Framework::JSON::loadJSONFromFile(path);
        if (value)
        {
            action(value, path);
            value->release();
        }
        progress->setProgress(progress->getProgress() + 1);
        progress->triggerUpdate();
    }
}

void loadAllJsonsFromDirectory(Framework::Text path,
    std::function<void(
        Framework::JSON::JSONValue* zValue, Framework::Text path)> action)
{
    Framework::ConsoleProgressBar* progressBar
        = new Framework::ConsoleProgressBar();
    Game::consoleHandler->addContent(
        progressBar, Framework::ConsoleContentPosition::Top);
    progressBar->triggerUpdate();
    progressBar->setMaxProgress(countAllJsonsInDirectory(path));
    progressBar->triggerUpdate();
    internalLoadAllJsonsFromDirectory(path, action, progressBar);
    progressBar->setMaxWidth(0);
    progressBar->triggerUpdate();
    Game::consoleHandler->removeContent(progressBar);
}