#include "AppMenu.h"

#include "../Settings.h"
#include "../PlayerCursor.h"
#include "../../Utils/AssetManager.h"

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


AppMenu::AppMenu(std::shared_ptr<MenuStack> menuStack, std::shared_ptr<Settings> settings, std::shared_ptr<sf::RenderWindow> renderWindow) :
	menuStack(menuStack),
	settings(settings),
	renderWindow(renderWindow) {

	const Asset& file = getResource(AssetName::data_fonts_pressstart_prstartk_ttf);

	this->pressStartFont = sf::Font(file.data, file.size);
}

void AppMenu::updateMetaBinds() {
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Enter)) {
		this->enterPressed = true;
		this->enterReleased = false;
	}
	else {
		this->enterReleased = this->enterPressed;
		this->enterPressed = false;
	}

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) {
		this->escPressed = true;
		this->escReleased = false;
	}
	else {
		this->escReleased = this->escPressed;
		this->escPressed = false;
	}
}

void AppMenu::placeText(sf::Text& text, const std::optional<PlayerCursor>& playerCursor, const sf::String& string, float xPos, float yPos, const std::optional<sf::Vector2u>& cursorPos) const {
	float sizeMultiplier = this->settings->getWindowSizeMultiplier();

	text.setString(string);
	if (playerCursor.has_value() && cursorPos.has_value()) {
		text.setOutlineThickness((playerCursor.value().getPosition() == cursorPos.value()) ? (sizeMultiplier / 2) : 0);
	}
	text.setOrigin(sf::Vector2f({0, text.getLocalBounds().size.y / 2}));
	text.setPosition(sf::Vector2f({sizeMultiplier * xPos, sizeMultiplier * yPos}));
	this->renderWindow->draw(text);
}

void AppMenu::placeTitle(sf::Text& text, const std::optional<PlayerCursor>& playerCursor, const sf::String& string, float yPos, const std::optional<sf::Vector2u>& cursorPos) const {
	float sizeMultiplier = this->settings->getWindowSizeMultiplier();

	text.setString(string);
	if (playerCursor.has_value() && cursorPos.has_value()) {
		text.setOutlineThickness((playerCursor.value().getPosition() == cursorPos.value()) ? (sizeMultiplier / 2) : 0);
	}
	text.setOrigin({text.getLocalBounds().getCenter().x, text.getLocalBounds().size.y / 2});
	text.setPosition(sf::Vector2f({sizeMultiplier * 40.f, sizeMultiplier * yPos}));
	this->renderWindow->draw(text);
}

sf::Color AppMenu::getColorOfBlock(Block block, int luminosityShift) const {
	Color rgbColor = BLOCKS_COLOR[block];
	return sf::Color(std::clamp(rgbColor.red + luminosityShift, 0, 255),
						std::clamp(rgbColor.green + luminosityShift, 0, 255),
						std::clamp(rgbColor.blue + luminosityShift, 0, 255));
}
