#include "GlobalExtern.h"

void ROMSelectInput() {
	ReadInput();

	if(analogScroll && !g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] && 
		!g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) {
			analogScroll = false;
			UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
			return;
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
		CancelSound();
		stopMovie();
		if(CustomSet) {
			GUIState = 13;
		}
		else if (CompanySet) {
			GUIState = 14;
		}
		else if (YearSet) {
			GUIState = 15;
		}
		else if (GenreSet) {
			GUIState = 16;
		}
		else {
			MenuSelected = 0;
			GUIState = MAIN_MENU;
			MenuBackground();
		}
		fadeOption = 0;
		fadeColor = 255;
		m_mp3player.pause(FALSE);
		
		return;
	}

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_DOWN)  {  
		if(GameSelected == GameDatabase.size() - 1)
			return;
		ClickSound();
		GameSelected++; 
		if(GameSelected >= GameDatabase.size()) 
			GameSelected = GameDatabase.size() - 1;
		UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
		return;
	}

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_UP)  { 
		if(GameSelected == 0)
			return;
		ClickSound();
		GameSelected--; 
		if(GameSelected < 0) 
			GameSelected = 0;
		UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
		return;
	}  

	if (g_Gamepads[DefaultController].fY2 < 0)  {
		ScrollSpeedCount++;
		if((ScrollSpeedCount % ScrollSpeed) == 0) {
			ScrollSpeedCount = 0;
			GameInfoDetailSelected += 1;
		}
		if(GameInfoDetailSelected >= GameInfoDetail.size()) 
			GameInfoDetailSelected = GameInfoDetail.size() - 1;
		return;
	}

	if (g_Gamepads[DefaultController].fY2 > 0)  {
		ScrollSpeedCount++;
		if((ScrollSpeedCount % ScrollSpeed) == 0) {
			ScrollSpeedCount = 0;
			GameInfoDetailSelected -= 1;
		}
		if(GameInfoDetailSelected < (GameInfoDetailNumLines / 2)) 
			GameInfoDetailSelected = (GameInfoDetailNumLines / 2);
		return;
	}  

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_LEFT  &&
		g_Gamepads[DefaultController].fX2 == 0 && 
		!(g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) && 
		!(g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER])) {  
			char c = GameDatabase[GameSelected].displayName[0];	  
			c = tolower(c);
			for(int i = GameSelected; i > 0; i--) {
				char n = GameDatabase[i].displayName[0];
				n = tolower(n);
				if(n <  c) {
					GameSelected = i;
					UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
					break;	
				}
			}
			return;
	} 

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_RIGHT &&
		g_Gamepads[DefaultController].fX2 == 0 && 
		!(g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) && 
		!(g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER])) { 
			char c = GameDatabase[GameSelected].displayName[0];	  
			c = tolower(c);
			for(int i = GameSelected; i < GameDatabase.size(); i++) {
				char n = GameDatabase[i].displayName[0];
				n = tolower(n);
				if(n > c) {
					GameSelected = i;
					UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
					break;
				}
			}
			return;
	} 		

	if (g_Gamepads[DefaultController].fX2 < 0)  {
		if(!PreviewSwitchValid())
			return;
		CyclePreview(-1);
		PreviewSwitch = true;
		UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
		if(!TexPreview) {
			for(int i = 0; i < 7; i++) {
				CyclePreview(-1);
				PreviewSwitch = true;
				UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
				if(TexPreview)
					break;
			}
		}
		return;
	}

	if (g_Gamepads[DefaultController].fX2 > 0)  {
		if(!PreviewSwitchValid())
			return;
		CyclePreview(1);
		PreviewSwitch = true;
		UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
		if(!TexPreview) {
			for(int i = 0; i < 7; i++) {
				CyclePreview(1);
				PreviewSwitch = true;
				UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
				if(TexPreview)
					break;
			}
		}
		return;
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_Y) {
		GameSelected = 0;
		UpdatePreview(GameDatabase[GameSelected].name, GameDatabase[GameSelected].parent);
		return;
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
		if(_tcscmp("", GameDatabase[0].name.c_str()) == 0) {
			return;
		}
		m_mp3player.stop();
		stopMovie();
		SaveIni();
		CreateDirectories(GameDatabase[GameSelected].name.c_str());
		FILE *f;
		f = fopen("Z:\\game.txt", "w+");
		fprintf(f, "%s\n", GameDatabase[GameSelected].name.c_str());
		fclose(f);
		PLAUNCH_DATA ldata ;
		memset( &ldata, 0, sizeof(PLAUNCH_DATA) ) ;

		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "Psikyo 68EC020") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "PS3-V1") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "PS5") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "FG-3") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "Kaneko 16-bit") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "PolyGameMaster") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "PolyGameMaster based") == 0) ||			
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "PS5V2") == 0))) {
				DisplayMessage("Please wait...");
				Device->PersistDisplay();
				XLaunchNewImage( "D:\\Psykio.xbe", ldata );
		}

		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "Neo Geo") == 0))) {
				Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
				Device->SetTexture(0,TexOption);
				DrawBackground();
				FontSetColour(0xffffff);
				FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
				//FontGUI(ConvertCharStringToWCHAR((char*)"This may take up to two minutes"), 320, 240 + vSpace, 640);
				Present();
				Device->PersistDisplay();
				XLaunchNewImage( "D:\\NeoGeoCPS2.xbe", ldata );
		}
		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "CPS2") == 0))) {
				Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
				Device->SetTexture(0,TexOption);
				DrawBackground();
				FontSetColour(0xffffff);
				FontGUI(ConvertCharStringToWCHAR((char*)"Please wait..."), 320, 240, 640);
				Present();
				Device->PersistDisplay();
				XLaunchNewImage( "D:\\NeoGeoCPS2.xbe", ldata );
		}
		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "Cave") == 0))) {
			DisplayMessage("Please wait...");
			Device->PersistDisplay();
			XLaunchNewImage( "D:\\Cave.xbe", ldata );
		}	
		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "Toaplan GP9001 based") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "Dual Toaplan GP9001 based") == 0))) {
			DisplayMessage("Please wait...");
			Device->PersistDisplay();
			XLaunchNewImage( "D:\\Toaplan.xbe", ldata );
		}
		if(((_tcscmp(GameDatabase[GameSelected].system.c_str(), "Taito-Z Old") == 0) ||
			(_tcscmp(GameDatabase[GameSelected].system.c_str(), "Taito Misc Old") == 0))) {
			DisplayMessage("Please wait...");
			Device->PersistDisplay();
			XLaunchNewImage( "D:\\Other.xbe", ldata );
		}
		DisplayMessage("Please wait...");
		Device->PersistDisplay();
		XLaunchNewImage( "D:\\default.xbe", ldata );
	}
	if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_START) {
		ConfirmSound();
		ImageSelectedMenu((char*)GameDatabase[GameSelected].name.c_str());
	}
	if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_BACK) {
		ConfirmSound();
		char fileName[260];
		sprintf(fileName,"%s%s%s", "D:\\info\\emulation\\", GameDatabase[GameSelected].name.c_str(), ".ini");
		LoadGuide(fileName, (char*)GameDatabase[GameSelected].name.c_str());
		DrawArcadeInfo();
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_WHITE) {
		AddToFavorites();
		SaveFavorites();
		while(1) {
			updateEffect();
			ReadInput();
			if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
				CancelSound();
				
				return;
			}

			Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
			Device->SetTexture(0,TexOption);
			DrawBackground();
			FontSetColour(0xffff00);
			//FontGUI(ConvertCharStringToWCHAR("Press \"A\" to exit"), 320, 240 + vSpace, 640);
			FontGUI(ConvertCharStringToWCHAR("The following game has been added to the favorites list:"), MenuPosX, 240, 640); 
			FontGUI(ConvertCharStringToWCHAR((char*)GameDatabase[GameSelected].displayName.c_str()), MenuPosX, 240 + 20, 640); 
			FontGUI(ConvertCharStringToWCHAR("Press \"B\" to return to the game list"), MenuPosX, 240 + 40, 640);
			Present();
		}
	}

	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) {
		if(GameSelected == GameDatabase.size() - 1)
			return;
		stopMovie();
		GameInfoDetail.clear();
		if(analogSpeed >= 1) { 
			analogSpeed = 0; 
		} 
		if(rightAnalog == 255)
			analogSpeed = scrollSpeed;
		else
			analogSpeed += ((float)rightAnalog/255.0f);
		GameSelected+=((int)analogSpeed); 
		if(GameSelected >= GameDatabase.size()) 
			GameSelected = GameDatabase.size() - 1;
		analogScroll = true;
		if(TexPreview) {
			TexPreview->Release();
			TexPreview = NULL;
		}
		return;
	}

	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) {
		if(GameSelected == 0)
			return;
		stopMovie();
		GameInfoDetail.clear();
		if(analogSpeed >= 1)  { 
			analogSpeed = 0;
		}
		if(leftAnalog == 255)
			analogSpeed = scrollSpeed;
		else
			analogSpeed += ((float)leftAnalog/255.0f);
		GameSelected-=((int)analogSpeed); if(GameSelected < 0) GameSelected = 0;
		analogScroll = true;
		if(TexPreview) {
			TexPreview->Release();
			TexPreview = NULL;
		}
		return;
	}
}

void DrawGameList() {
	FontSetColour(0xffff00);
	FontCenteredText(ConvertCharStringToWCHAR((char*)GameDatabase[GameSelected].displayName.c_str()),320, ROMPosY, 640);
	int y = GameListY;
	DWORD color;
	int start = 0;

	if(GameSelected > (GameListCount / 2) && (GameDatabase.size() > GameListCount)) {
		start += (GameSelected  - (GameListCount / 2));
	}

	if((GameSelected > ((GameDatabase.size()-1) - (GameListCount / 2))) && (GameDatabase.size() > GameListCount)) {
		start = (GameDatabase.size() - GameListCount);
	}

	for(int i = start; i <  start + GameListCount; i++) {
		if(i == GameDatabase.size()) return;
		if(i ==GameSelected) {
			color = 0xffff00; 
		}
		else {
			if(HighlightParent == 1) {
				if(_tcscmp(GameDatabase[i].parent.c_str(), "NULL") == 0)
					color = 0x00ff00;
				else
					color = 0xffffff;
			}
			else {
				color = 0xffffff;
			}
		}
		WCHAR msg[1024]={0};

		std::string t = GameDatabase[i].displayName;
		for(int r = 0; r < 1024; r++) {
			if((t.c_str())[r] == '\0') {
				msg[r] = '\0';
				break;
			}
			msg[r] = (t.c_str())[r];
		}
		FontSetColour(color);
		FontText(msg,GameListX, y, GameListWidth);
		y+=vSpace;
	}
}

void DrawROMList(int Mode) {
	Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	Device->Clear(0,NULL,D3DCLEAR_TARGET,0,1.0f,0);
	Device->SetTexture(0,TexROMBrowser);
	DrawBackground();

	if(fadeColor > 0) {
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		fade = true;
		fadeColor -=fadeSpeed;
		if(fadeColor < fadeSpeed) { fadeColor = 0; resumeGUI = false; }
		if(resumeGUI || CustomSet || CompanySet || YearSet || GenreSet) {
			Device->SetTexture(0,TexOption);
		}
		else {
			Device->SetTexture(0,TexMainMenu);
		}
		DrawBackground();
		fade = false;
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		Present();
		if(setDisplay) {
			setDisplay = false;
			Device->SetFlickerFilter(FlickerFilter);
			Device->SetSoftDisplayFilter(Soften);
		}
		return;
	}
	else {	
		if(TexPreview) {
			if(videoRender && MovieEnabled) {
				Device->SetTexture(0,TexPreview);
				if(SourceWidth < SourceHeight) {
					MakeVertexListPreviewVertical();
				}
				else {
					MakeVertexListPreview();
				}
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
				Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
				Device->SetTexture(0,TexPreviewBorder);
				if(SourceWidth < SourceHeight) {
					MakeVertexListPreviewBorderVertical();
				}
				else {
					MakeVertexListPreviewBorder();
				}
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
				Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
			}
			else {
				Device->SetTexture(0,TexPreview);
				if(SourceWidth < SourceHeight) {
					MakeVertexListAlternatePreviewVertical();
				}
				else {
					MakeVertexListAlternatePreview();
				}
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
				Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
				Device->SetTexture(0,TexPreviewBorder);
				if(SourceWidth < SourceHeight) {
					MakeVertexListAlternatePreviewBorderVertical();
				}
				else {
					MakeVertexListAlternatePreviewBorder();
				}
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
				Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
				Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
			}
		}
		Device->SetTexture(0,TexROMBorder);
		MakeVertexListROMBorder();
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetTexture(0,TexSelectedBorder);
		MakeVertexListSelectedBorder();
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		if(Mode == 1)
			DrawGameFavoriteList();
		else
			DrawGameList();
		if(videoRender && MovieEnabled) {
			drawMovie();
			Device->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
			Device->SetTexture(0,TexVideoBorder);
			if(!TexPreview) {
				MakeVertexListVideoBorder();
			}
			else {
				MakeVertexListDualVideoBorder();
			}
			Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
			Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
			Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
		}
		Device->SetTexture(0,TexAnimatedLogo);
		MakeVertexListAnimatedLogo(false);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
		Device->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);
		Device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
	}
	Present();
	if(setDisplay) {
		setDisplay = false;
		Device->SetFlickerFilter(FlickerFilter);
		Device->SetSoftDisplayFilter(Soften);
	}
}

void DrawROMSelectMenu() {
	DrawROMList(0);
}

void ROMSelectMenu() {
	DrawROMSelectMenu();
	ROMSelectInput();
}
