//
// Created by sebastian on 30.07.26.
//

#include "SceneManager.h"

#include <iostream>

#include "spdlog/spdlog.h"

void engine::SceneManager::switchTo(std::unique_ptr<Scene> scene, std::function<void()> onSceneLoaded) {
    onSceneLoaded = std::move(onSceneLoaded);
    nextScene = std::move(scene);

    std::vector<AssetRequest> requestedAssets = nextScene->getRequiredAssets();
    spdlog::debug("Requested Assets: {}", requestedAssets.size());

    for (AssetRequest & request : requestedAssets) {
        assetLoader.scheduleAsset(request);
    }

    assetLoader.start();
}

void engine::SceneManager::update(float deltaTime)  {
    if (nextScene) {
        auto uploadedAssets = assetLoader.processUploadQueue(2);
        std::cout << "Uploaded Assets: " << uploadedAssets.size() << std::endl;
        for (const auto& asset : uploadedAssets) {
            nextScene->onRegisterLoadedAsset(asset);
        }

        if (assetLoader.getProgress().isDone()) {
            if (currentScene) {
                currentScene->onExit();
            }

            currentScene = std::move(nextScene);
            nextScene = nullptr;
            currentScene->onEnter();

            assetLoader.stop();

            if (onSceneLoaded) {
                onSceneLoaded();
                onSceneLoaded = nullptr;
            }
        }
    }

    if (currentScene) {
        currentScene->onUpdate(deltaTime);
    }
}

void engine::SceneManager::render() const {
    if (currentScene) {
        currentScene->onRender();
    }
}

float engine::SceneManager::getTransitionProgress() const {
    return assetLoader.getProgress().fraction();
}
