#include <SFML/Graphics.hpp>

#include "DangerousRacers/SceneManager.h"
#include "DangerousRacers/GameManager.h"
#include "DangerousRacers/Scenes/GameOver.h"
#include "DangerousRacers/Scenes/MainMenu.h"
#include "DangerousRacers/Scenes/studio_splashscreen.h"
#include "DangerousRacers/Scenes/TutorialOver.h"
#include "DangerousRacers/Scenes/Levels/level_one.h"
#include "DangerousRacers/Scenes/Levels/tutorial_level.h"

int main() {
    // Setup View related stuffs
    sf::Vector2u RESOLUTION(405, 720);
    sf::VideoMode VIDEO_MODE = sf::VideoMode::getDesktopMode();
    sf::RenderWindow GAME_WINDOW;

    GAME_WINDOW.create(sf::VideoMode(RESOLUTION.x, RESOLUTION.y), "SFML Game", sf::Style::None);

    GAME_WINDOW.setMouseCursorVisible(true);
    GAME_WINDOW.setMouseCursorGrabbed(true);

    // Make sure the background is black
    sf::RectangleShape bg_rect(sf::Vector2f(static_cast<float>(RESOLUTION.x), static_cast<float>(RESOLUTION.y)));
    bg_rect.setFillColor(sf::Color::Black);

    // THe big bad delta clock
    sf::Clock deltaClock;

    auto gameManager = std::make_unique<GameManager>();
    auto sceneManager = std::make_unique<SceneManager>(GAME_WINDOW, *gameManager);

    sceneManager->addScene("StudioSplashScreenScene",[&] {
        return std::make_unique<StudioSplashScreenScene>(*sceneManager);
    });
    sceneManager->addScene("MainMenu",[&] {
        return std::make_unique<MainMenuScene>(*sceneManager);
    });
    sceneManager->addScene("DebugLevelScene",[&] {
       return std::make_unique<TutorialLevelScene>(*sceneManager);
    });
    sceneManager->addScene("LevelOne",[&] {
       return std::make_unique<LevelOneScene>(*sceneManager);
    });
    sceneManager->addScene("TutorialOverScene",[&] {
        return std::make_unique<TutorialOverScene>(*sceneManager);
    });

    sceneManager->changeScene("StudioSplashScreenScene");

    while (GAME_WINDOW.isOpen()) {
        sf::Event event;
        while (GAME_WINDOW.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                sceneManager->_quit();
            }

            if ((event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)) {
                if (sceneManager->getCurrentScene() != "MainMenu") sceneManager->changeScene("MainMenu");
                else sceneManager->_quit();
            }

            sceneManager->eventHandler(event);
        }

        float deltaTime = deltaClock.restart().asSeconds();

        sceneManager->update(deltaTime);

        GAME_WINDOW.clear();
        GAME_WINDOW.draw(bg_rect);
        sceneManager->render(GAME_WINDOW);
        GAME_WINDOW.display();

        sceneManager->applySceneChange();
    }

    return 0;
}
