#include "GraphApp.h"

#include "AppMenus/AppMenu.h"
#include "AppMenus/StartUpAppMenu.h"
#include "Settings.h"

#include <stack>
#include <memory>
#include <SFML/Graphics.hpp>

static const double TIME_BETWEEN_FRAMES = (1000.f / FRAMES_PER_SECOND);


GraphApp::GraphApp() {
    this->settings = std::make_shared<Settings>(false);
    this->menuStack = std::make_shared<MenuStack>();
    this->renderWindow = std::make_shared<sf::RenderWindow>();
}

void GraphApp::run() {
    this->settings->changeVideoMode(*this->renderWindow);
    this->menuStack->push(std::make_shared<StartUpAppMenu>(this->menuStack, this->settings, this->renderWindow));

    bool quit = false;
    double timeAtNextFrame = 0;
    sf::Clock clock;
    while (!quit) {
        while (const std::optional event = this->renderWindow->pollEvent()) {
            if (event->is<sf::Event::Closed>()) {
                quit = true;
            }
        }

        if (!quit) {
            if (clock.getElapsedTime().asMilliseconds() > timeAtNextFrame) {
                this->menuStack->top()->computeFrame();

                if (this->menuStack->empty()) {
                    quit = true;
                }
                else {
                    this->menuStack->top()->drawFrame();
                }

                while (clock.getElapsedTime().asMilliseconds() > timeAtNextFrame) {
                    timeAtNextFrame += TIME_BETWEEN_FRAMES;
                }
            }
        }   
    }
    this->settings->saveSettingsToFile();
    renderWindow->close();
}
