#include "StartUpAppMenu.h"

#include "AppMenu.h"
#include "MainAppMenu.h"
#include "../PlayerCursor.h"

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


StartUpAppMenu::StartUpAppMenu(std::shared_ptr<MenuStack> menuStack, std::shared_ptr<Settings> settings, std::shared_ptr<sf::RenderWindow> renderWindow) :
    AppMenu(menuStack, settings, renderWindow),
    playerCursor({MAXIMUM_PIECES_SIZE + 1}) {

    this->playerCursor.goToPosition({(unsigned int) std::clamp(this->settings->getLoadablePiecesSize(), MINIMUM_PIECES_SIZE, MAXIMUM_PIECES_SIZE), 0u});
}

void StartUpAppMenu::computeFrame() {
    this->updateMetaBinds();
    this->playerCursor.updatePosition();

    if (this->playerCursor.getPosition().x < MINIMUM_PIECES_SIZE) {
        if (this->playerCursor.movedLeft()) {
            this->playerCursor.goToPosition({MAXIMUM_PIECES_SIZE, 0});
        }
        else {
            this->playerCursor.goToPosition({MINIMUM_PIECES_SIZE, 0});
        }
    }

    if (this->enterReleased) {
        this->settings->loadSettingsFromFile(true, {this->playerCursor.getPosition().x});
        this->menuStack->pop();

        if (this->settings->hasLoadedPieces()) {
            this->menuStack->push(std::make_shared<MainAppMenu>(this->menuStack, this->settings, this->renderWindow));
        }
        else {
            std::cout << "ERROR: COULD NOT LOAD PIECES" << std::endl;
            std::cout << "ARGUMENT WAS: " << this->playerCursor.getPosition().x << std::endl;
        }
    }
    else if (this->escReleased) {
        this->menuStack->pop();
    }
}

void StartUpAppMenu::drawFrame() const {
    this->renderWindow->clear(sf::Color(200, 200, 200));

    sf::Text text(this->pressStartFont, "", this->settings->getWindowSizeMultiplier() * 2);
    text.setFillColor(sf::Color(0, 0, 0));
    text.setOutlineColor(sf::Color(255, 255, 255));

    this->placeTitle(text, {}, "SELECT THE LOADED PIECES MAXIMUM SIZE", 10.f, {});
    this->placeTitle(text, this->playerCursor, "< " + std::to_string(this->playerCursor.getPosition().x) + " >", 25.f, this->playerCursor.getPosition());
    
    text.setOutlineColor({0, 0, 0});
    if (this->playerCursor.getPosition().x <= 10) {
        text.setFillColor({0, 255, 0});
        this->placeTitle(text, {}, "LOW LOAD TIME", 40.f, {});
    }
    else if (this->playerCursor.getPosition().x <= 13) {
        text.setFillColor({255, 255, 0});
        this->placeTitle(text, {}, "MEDIUM LOAD TIME", 40.f, {}); 
    }
    else {
        text.setFillColor({255, 0, 0});
        this->placeTitle(text, {}, "LONG LOAD TIME", 40.f, {}); 
    }

    this->renderWindow->display();
}
