#include <iostream>
#include <ostream>
#include <DangerousRacers/SceneManager.h>
#include "DangerousRacers/Scene.h"

SceneManager::SceneManager(sf::RenderWindow& gameWindow, GameManager& gameManager) :
gameWindow(gameWindow), gameManager(gameManager) {

}

void SceneManager::applySceneChange() {
    if (!pendingSceneChange) return;

    const auto& factory = sceneFactories.at(pendingScene);
    if (currentScene != nullptr) currentScene->leave();

    currentScene = factory();
    activeScene = pendingScene;
    currentScene->start();

    pendingSceneChange = false;
}

void SceneManager::changeScene(const std::string& sceneName) {
    std::cout << "Changing scene to " << sceneName << std::endl;
    const auto& factory = sceneFactories.at(sceneName);
    if (!factory) {
        std::cout << "Scene not found?" << std::endl;
        return;
    };
    pendingScene = sceneName;
    pendingSceneChange = true;
}

void SceneManager::update(const float deltaTime) const {
    if (currentScene == nullptr) return;
    currentScene->update(deltaTime);
}

void SceneManager::render(sf::RenderWindow& window) const {
    if (currentScene == nullptr) return;
    currentScene->render(window);
}

void SceneManager::eventHandler(sf::Event &event) const {
    if (currentScene == nullptr) return;
    currentScene->eventHandler(event);
}

void SceneManager::_quit() {
    sceneFactories.clear();
    currentScene = nullptr;
    this->gameWindow.close();
}
