#include "gamestate_title.h"
#include <SDL2/SDL_blendmode.h>  // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_error.h>      // for SDL_GetError
#include <SDL2/SDL_pixels.h>     // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_scancode.h>   // for SDL_SCANCODE_1, SDL_SCANCODE_2
#include <SDL2/SDL_timer.h>      // for SDL_GetTicks
#include <iostream>              // for basic_ostream, operator<<, basic_ios
#include "asset.h"               // for Asset
#include "cheevos.h"             // for cheevos_t, Cheevos
#include "const.h"               // for PLAY_AREA_CENTER_X, GAMECANVAS_WIDTH
#include "input.h"               // for Input, inputs_e, REPEAT_FALSE, REPEA...
#include "resource.h"            // for Resource
#include "screen.h"              // for Screen
#include "sprite.h"              // for Sprite
#include "text.h"                // for Text, TXT_CENTER, TXT_COLOR
#include "texture.h"             // for Texture
#include "utils.h"               // for color_t, stringToColor, options_t

// Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
	// Copia la dirección de los objetos
	this->resource = resource;
	this->renderer = renderer;
	this->screen = screen;
	this->asset = asset;
	this->input = input;
	this->options = options;
	this->section = section;

	// Reserva memoria para los punteros
	eventHandler = new SDL_Event();
	cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"));
	if (options->palette == p_zxspectrum)
	{
		texture = resource->getTexture("title_logo.png");
	}
	else if (options->palette == p_zxarne)
	{
		texture = resource->getTexture("title_logo.png");
	}
	sprite = new Sprite(0, 0, texture->getWidth(), texture->getHeight(), texture, renderer);
	text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer);
	infoText = new Text(resource->getOffset("subatomic.txt"), resource->getTexture("subatomic.png"), renderer);

	// Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo
	bgTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
	if (bgTexture == nullptr)
	{
		if (options->console)
		{
			std::cout << "Error: bgTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
		}
	}
	SDL_SetTextureBlendMode(bgTexture, SDL_BLENDMODE_BLEND);

	// Carga la surface con los gráficos de la pantalla de carga
	pInit(renderer, 256, 128);
	loading_screen = pLoadSurface(asset->get("loading_screen_color.gif").c_str());
	pLoadPal(asset->get("loading_screen_color.gif").c_str());
	pSetSource(loading_screen);

	// Inicializa variables
	counter = 0;
	state = section->subsection == SUBSECTION_TITLE_WITH_LOADING_SCREEN ? show_loading_screen : show_menu;
	section->name = SECTION_TITLE;
	section->subsection = 0;
	ticks = 0;
	ticksSpeed = 15;
	marqueeSpeed = 3;
	initMarquee();
	showCheevos = false;

	// Crea y rellena la textura para mostrar los logros
	createCheevosTexture();

	// Cambia el color del borde
	screen->setBorderColor(stringToColor(options->palette, "black"));

	// Rellena la textura de fondo con todos los gráficos
	fillTexture();
}

// Destructor
Title::~Title()
{
	delete cheevos;
	delete eventHandler;
	delete sprite;
	delete cheevosSprite;
	delete cheevosTexture;
	delete text;
	delete infoText;
	pDeleteSurface(loading_screen);
	SDL_DestroyTexture(bgTexture);
}

// Inicializa la marquesina
void Title::initMarquee()
{
	letters.clear();
	longText = "HEY JAILERS!! IT'S 2022 AND WE'RE STILL ROCKING LIKE IT'S 1998!!! HAVE YOU HEARD IT? JAILGAMES ARE BACK!! YEEESSS BACK!! MORE THAN 10 TITLES ON JAILDOC'S KITCHEN!! THATS A LOOOOOOT OF JAILGAMES, BUT WHICH ONE WILL STRIKE FIRST? THERE IS ALSO A NEW DEVICE TO COME THAT WILL BLOW YOUR MIND WITH JAILGAMES ON THE GO: P.A.C.O. BUT WAIT! WHAT'S THAT BEAUTY I'M SEEING RIGHT OVER THERE?? OOOH THAT TINY MINIASCII IS PURE LOVE!! I WANT TO LICK EVERY BYTE OF IT!! OH SHIT! AND DON'T FORGET TO BRING BACK THOSE OLD AND FAT MS-DOS JAILGAMES TO GITHUB TO KEEP THEM ALIVE!! WHAT WILL BE THE NEXT JAILDOC RELEASE? WHAT WILL BE THE NEXT PROJECT TO COME ALIVE?? OH BABY WE DON'T KNOW BUT HERE YOU CAN FIND THE ANSWER, YOU JUST HAVE TO COMPLETE JAILDOCTOR'S DILEMMA ... COULD YOU?";
	for (int i = 0; i < (int)longText.length(); ++i)
	{
		letter_t l;
		l.letter = longText.substr(i, 1);
		l.x = 256;
		l.enabled = false;
		letters.push_back(l);
	}
	letters[0].enabled = true;
}

// Comprueba el manejador de eventos
void Title::checkEvents()
{
	// Comprueba los eventos que hay en la cola
	while (SDL_PollEvent(eventHandler) != 0)
	{
		// Evento de salida de la aplicación
		if (eventHandler->type == SDL_QUIT)
		{
			section->name = SECTION_QUIT;
			break;
		}

		// Solo se comprueban estas teclas si no está activo el menu de logros
		if (eventHandler->type == SDL_KEYDOWN)
		{
			if (!showCheevos)
			{
				switch (eventHandler->key.keysym.scancode)
				{
				case SDL_SCANCODE_1:
					section->name = SECTION_GAME;
					section->subsection = 0;
					break;

				case SDL_SCANCODE_2:
					showCheevos = true;
					break;

				default:
					break;
				}
			}
		}
	}
}

// Comprueba las entradas
void Title::checkInput()
{
	if (showCheevos)
	{
		if (input->checkInput(input_down, REPEAT_TRUE))
		{
			moveCheevosList(1);
		}
		else if (input->checkInput(input_up, REPEAT_TRUE))
		{
			moveCheevosList(0);
		}
	}

	if (input->checkInput(input_exit, REPEAT_FALSE))
	{
		if (showCheevos)
		{
			hideCheevosList();
			counter = 0;
		}
		else
		{
			section->name = SECTION_QUIT;
		}
	}

	else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
	{
		screen->toggleBorder();
		resource->reLoadTextures();
	}

	else if (input->checkInput(input_toggle_videomode, REPEAT_FALSE))
	{
		screen->toggleVideoMode();
		resource->reLoadTextures();
	}

	else if (input->checkInput(input_toggle_shaders, REPEAT_FALSE))
	{
		screen->toggleShaders();
	}

	else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
	{
		screen->decWindowSize();
		resource->reLoadTextures();
	}

	else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
	{
		screen->incWindowSize();
		resource->reLoadTextures();
	}

	else if (input->checkInput(input_toggle_palette, REPEAT_FALSE))
	{
		switchPalette();
	}

	else if (input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_pause, REPEAT_FALSE))
	{
		if (state == show_loading_screen)
		{
			state = fade_loading_screen;
		}
	}
}

// Actualiza la marquesina
void Title::updateMarquee()
{
	for (int i = 0; i < (int)letters.size(); ++i)
	{
		if (letters[i].enabled)
		{
			letters[i].x -= marqueeSpeed;
			if (letters[i].x < -10)
			{
				letters[i].enabled = false;
			}
		}
		else
		{
			if (i > 0 && letters[i - 1].x < 256 && letters[i - 1].enabled)
			{
				letters[i].enabled = true;
				letters[i].x = letters[i - 1].x + text->lenght(letters[i - 1].letter) + 1;
			}
		}
	}

	// Comprueba si ha terminado la marquesina y la reinicia
	if (letters[letters.size() - 1].x < -10)
	{ // Inicializa la marquesina
		initMarquee();
	}
}

// Dibuja la marquesina
void Title::renderMarquee()
{
	for (auto l : letters)
	{
		if (l.enabled)
		{
			text->writeColored(l.x, 184, l.letter, stringToColor(options->palette, "white"));
		}
	}
}

// Dibuja la linea de información inferior
void Title::renderInfo()
{
	const std::string version = "v.1.09";
	const int x = GAMECANVAS_WIDTH - infoText->lenght(version) - 1;
	infoText->write(x, 1, version);
}

// Actualiza las variables
void Title::update()
{
	// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
	if (SDL_GetTicks() - ticks > ticksSpeed)
	{
		// Actualiza el contador de ticks
		ticks = SDL_GetTicks();

		// Comprueba las entradas
		checkInput();

		// Actualiza las notificaciones
		screen->updateNotifier();

		// Incrementa el contador
		counter++;

		switch (state)
		{
		case show_loading_screen:
			if (counter == 500)
			{
				counter = 0;
				state = fade_loading_screen;
			}
			break;

		case fade_loading_screen:
			if (counter % 4 == 0)
				if (pFadePal())
				{
					counter = 0;
					state = show_menu;
				}
			break;

		case show_menu:
			// Actualiza la marquesina
			updateMarquee();

			// Si el contador alcanza cierto valor, termina la seccion
			if (counter == 2200)
			{
				if (!showCheevos)
				{
					section->name = SECTION_CREDITS;
					section->subsection = 0;
				}
			}
			break;

		default:
			break;
		}
	}
}

// Dibuja en pantalla
void Title::render()
{
	// Prepara para empezar a dibujar en la textura de juego
	screen->start();
	screen->clean(stringToColor(options->palette, "black"));

	if (state == show_menu)
	{
		// Dibuja la textura de fondo
		SDL_RenderCopy(renderer, bgTexture, nullptr, nullptr);

		// Dibuja la marquesina
		renderMarquee();

		// Dibuja la información de logros
		if (showCheevos)
		{
			cheevosSprite->render();
		}
	}
	else
	{
		// Dibuja la pantalla de carga
		pCls(4);
		pBlit(0, 0, 0, 0, 256, 128);
		pFlip(renderer);

		// Dibuja el logo del título
		sprite->render();
	}

	// Vuelca el contenido del renderizador en pantalla
	screen->render();
}

// Bucle para el logo del juego
void Title::run()
{
	while (section->name == SECTION_TITLE)
	{
		update();
		checkEvents();
		render();
	}
}

// Recarga las texturas
void Title::reLoadTextures()
{
	// Carga la textura adecuada
	if (options->palette == p_zxspectrum)
	{
		texture = resource->getTexture("loading_screen_color.png");
	}
	else if (options->palette == p_zxarne)
	{
		texture = resource->getTexture("loading_screen_color_zxarne.png");
	}

	texture->reLoad();
}

// Cambia la paleta
void Title::switchPalette()
{
	if (options->palette == p_zxspectrum)
	{
		options->palette = p_zxarne;
		sprite->setTexture(resource->getTexture("loading_screen_color_zxarne.png"));
	}
	else
	{
		options->palette = p_zxspectrum;
		sprite->setTexture(resource->getTexture("loading_screen_color.png"));
	}

	// Cambia el color del borde
	screen->setBorderColor(stringToColor(options->palette, "bright_blue"));
}

// Desplaza la lista de logros
void Title::moveCheevosList(int direction)
{
	const int speed = 2;
	cheevosTextureView.y = direction == 0 ? cheevosTextureView.y - speed : cheevosTextureView.y + speed;

	const int bottom = cheevosTexture->getHeight() - cheevosTextureView.h;
	if (cheevosTextureView.y < 0)
	{
		cheevosTextureView.y = 0;
	}
	else if (cheevosTextureView.y > bottom)
	{
		cheevosTextureView.y = bottom;
	}

	cheevosSprite->setSpriteClip(cheevosTextureView);
}

// Rellena la textura de fondo con todos los gráficos
void Title::fillTexture()
{
	// Coloca el puntero del renderizador sobre la textura
	SDL_SetRenderTarget(renderer, bgTexture);

	// Rellena la textura de color
	const color_t c = stringToColor(options->palette, "black");
	SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
	SDL_RenderClear(renderer);

	// Pinta el gráfico del titulo a partir del sprite
	sprite->render();

	// Escribe el texto en la textura
	const color_t textColor = stringToColor(options->palette, "green");
	const int textSize = text->getCharacterSize();
	text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor);
	text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor);
	text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.REDEFINE KEYS", 1, textColor);
	text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 20 * textSize, "ESC.EXIT GAME", 1, textColor);

	// Devuelve el puntero del renderizador a su sitio
	SDL_SetRenderTarget(renderer, nullptr);
}

// Crea y rellena la textura para mostrar los logros
void Title::createCheevosTexture()
{
	// Crea la textura con el listado de logros
	const std::vector<cheevos_t> cheevosList = cheevos->list();
	const int cheevosTextureWidth = 200;
	const int cheevosTextureViewHeight = 110;
	const int cheevosTexturePosY = 73;
	const int cheevosPadding = 10;
	const int cheevoHeight = cheevosPadding + (infoText->getCharacterSize() * 2) + 1;
	const int cheevosTextureHeight = (cheevoHeight * cheevosList.size()) + 2 + infoText->getCharacterSize() + 8;
	cheevosTexture = new Texture(renderer);
	cheevosTexture->createBlank(renderer, cheevosTextureWidth, cheevosTextureHeight, SDL_TEXTUREACCESS_TARGET);
	cheevosTexture->setAsRenderTarget(renderer);
	cheevosTexture->setBlendMode(SDL_BLENDMODE_BLEND);

	// Rellena la textura con color sólido
	const color_t cheevosBGColor = stringToColor(options->palette, "black");
	SDL_SetRenderDrawColor(renderer, cheevosBGColor.r, cheevosBGColor.g, cheevosBGColor.b, 0xFF);
	SDL_RenderClear(renderer);

	// Escribe la lista de logros en la textura
	const std::string cheevosOwner = "LOCAL ACHIEVEMENTS";
	const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(cheevos->unlocked()) + " / " + std::to_string(cheevos->count()) + ")";
	int pos = 2;
	infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTexture->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options->palette, "bright_green"));
	pos += infoText->getCharacterSize();
	const color_t cheevoLockedColor = stringToColor(options->palette, "white");
	const color_t cheevoUnlockedColor = stringToColor(options->palette, "bright_green");
	color_t cheevoColor;
	SDL_SetRenderDrawColor(renderer, cheevoLockedColor.r, cheevoLockedColor.g, cheevoLockedColor.b, 0xFF);
	const int lineX1 = (cheevosTextureWidth / 7) * 3;
	const int lineX2 = lineX1 + ((cheevosTextureWidth / 7) * 1);

	for (auto cheevo : cheevosList)
	{
		cheevoColor = cheevo.completed ? cheevoUnlockedColor : cheevoLockedColor;
		pos += cheevosPadding;
		int half = cheevosPadding / 2;
		SDL_RenderDrawLine(renderer, lineX1, pos - half - 1, lineX2, pos - half - 1);
		infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.caption, 1, cheevoColor);
		pos += infoText->getCharacterSize() + 1;
		infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.description, 1, cheevoColor);
		pos += infoText->getCharacterSize();
	}

	// Crea el sprite para el listado de logros
	cheevosSprite = new Sprite((GAMECANVAS_WIDTH - cheevosTexture->getWidth()) / 2, cheevosTexturePosY, cheevosTexture->getWidth(), cheevosTexture->getHeight(), cheevosTexture, renderer);
	cheevosTextureView = {0, 0, cheevosTexture->getWidth(), cheevosTextureViewHeight};
	cheevosSprite->setSpriteClip(cheevosTextureView);
}

// Oculta la lista de logros
void Title::hideCheevosList()
{
	showCheevos = false;
	cheevosTextureView.y = 0;
	cheevosSprite->setSpriteClip(cheevosTextureView);
}