#include "modulestaticscreen.h"

#include "jgame.h"
#include "jdraw8.h"
#include "jinput.h"
#include "jsound.h"
#include <stdlib.h>
#include <string>

ModuleStaticScreen::ModuleStaticScreen( Info* info ) {
	this->info = info;
}

ModuleStaticScreen::~ModuleStaticScreen(void) {
}

int ModuleStaticScreen::Go() {

	switch( this->info->estat_joc ) {
		case ESTAT_ICEKAS:
			doIcekas();
			break;
		case ESTAT_LOGO:
			doLogo();
			break;
	}

	JD8_FadeOut();

	if( JG_Quitting() ) {
		return ESTAT_EIXIR;
	} else {
		switch (this->info->estat_joc) {
			case ESTAT_ICEKAS: return ESTAT_LOGO; break;
			case ESTAT_LOGO: return ESTAT_MENU; break;
		}
	}
    return 0;
}

const int minim( const int a, const int b ) {
	if( b < a ) { return b; } else { return a; }
}

void ModuleStaticScreen::doIcekas() {

	bool eixir = false;

	JS_LoadMusic("mlogo.xm");
	JS_PlayMusic(1);

	JD8_Surface gfx = JD8_LoadSurface( "logo.gif" );
	JD8_Palette pal = JD8_LoadPalette( "logo.gif" );

	JD8_ClearScreen( 0 );
	JD8_Flip();

	// FADE IN
	JD8_Blit(gfx);
	JG_SetUpdateTicks(8);
	while (!JD8_FadeToPalAsync(pal) && !eixir) {
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	// DELAY
	JG_SetUpdateTicks(100);
	int contador = 20;
	while (contador > 0 && !eixir) {
		contador--;
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	// FADE OUT
	JG_SetUpdateTicks(2);
	while (!JD8_FadeOutAsync() && !eixir) {
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	JD8_FreeSurface( gfx );
	free(pal);
}

void ModuleStaticScreen::doLogo() {

	bool eixir = false;

	JD8_Surface gfx = JD8_LoadSurface("titol.gif");
	JD8_Palette pal = JD8_LoadPalette("titol.gif");

	JD8_ClearScreen(0);
	JD8_Flip();

	// FADE IN
	JD8_Blit(gfx);
	JG_SetUpdateTicks(8);
	while (!JD8_FadeToPalAsync(pal) && !eixir) {
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	// DELAY
	JG_SetUpdateTicks(100);
	int contador = 20;
	while (contador > 0 && !eixir) {
		contador--;
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	// FADE OUT
	JG_SetUpdateTicks(2);
	while (!JD8_FadeOutAsync() && !eixir) {
		while (!JG_ShouldUpdate()) { JI_Update(); if (JI_AnyKey() || JG_Quitting()) { eixir = true; } }
	}

	JD8_FreeSurface(gfx);
	free(pal);
}
