#include <Display/WidgetDisplay/ShutdownDisplay/ShutdownDisplay.hpp>
#include <Widget/Layout/Center/Center.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Label/Label.hpp>
#include <Display/WidgetDisplay/MainMenuDisplay/MainMenuDisplay.hpp>
#include <Utilities/Utilities.hpp>

ShutdownDisplay::ShutdownDisplay(std::shared_ptr<World> world) :
    world(world),
    lastProgressCheckTime(std::chrono::steady_clock::now())
{
    setWidget(
        new Center(
            new Column(
                new Label("Closing world...")
            )
        )
    );
}

void ShutdownDisplay::update()
{
    if (isWorldClean)
    {
        if (tasksFinished.load())
        {
            world->doShutdownSanityChecks();
            Display::navPop();
        }

        return;
    }

    world->housekeep();
    if (world->getPurgeQueueSize() == 0 && world->isShutdownReady())
    {
        isWorldClean = true;

        afterAsyncBarrier(AsyncBarrier::CurrentlyDispatched, [this]()
        {
            tasksFinished = true;
        });

        return;
    }

    if (std::chrono::steady_clock::now() - lastProgressCheckTime > purgeTimeout)
    {
        Log::warn("Chunk purging is taking a very long time, dumping the purge queue...");
        world->dumpPurgeQueue();

        Log::debug("The purge timeout will now be reset, will check again soon.");
        lastProgressCheckTime = std::chrono::steady_clock::now();
    }
}

void ShutdownDisplay::onQuit()
{
    // NOP: Do not allow quitting during the shutdown display.
}