#include "GlobalExtern.h"

void  RemoveFromFavorites() {
	if(FavoritesDatabase.size() == 1 && GameFavoriteSelected == 0) {
		FavoritesDatabase.clear();
		GameDBEntry e;
		e.name = "";
		e.displayName = "No Favorites Found";
		FavoritesDatabase.push_back(e);
		UpdatePreview(FavoritesDatabase[GameFavoriteSelected].name, FavoritesDatabase[GameFavoriteSelected].parent);
		return;
	}
	if(FavoritesDatabase.size() > 1) {
		FavoritesDatabase.erase(FavoritesDatabase.begin()+GameFavoriteSelected);
	}
	if(GameFavoriteSelected > 0) GameFavoriteSelected--;
	UpdatePreview(FavoritesDatabase[GameFavoriteSelected].name, FavoritesDatabase[GameFavoriteSelected].parent);
}

bool BuildFavorites() {
	FavoritesDatabase.clear();
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\favorites.ini");
	ifstream f(fileName);
	if(!f){
		GameDBEntry game;
		game.name = "";
		game.displayName = "No Favorites Found";
		game.date = "";
		game.manufacturer = "";
		game.system = "";
		game.genre = "";
		game.parent = "";
		FavoritesDatabase.push_back(game);
		return false;
	}
	char line[2048];
	for(int i = 0; i < 2048; i++) line[i] = '\0';
	f.getline(line, 2048);
	int e = atoi(line);
	if(e == 0) {
		GameDBEntry game;
		game.name = "";
		game.displayName = "No Favorites Found";
		game.date = "";
		game.manufacturer = "";
		game.system = "";
		game.genre = "";
		game.parent = "";
		FavoritesDatabase.push_back(game);
		f.close();
		return true;
	}

	for(int i = 0; i < e; i++) {
		GameDBEntry game;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.name = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.displayName = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.date = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.manufacturer = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.system = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.genre = line;
		for(int i = 0; i < 2048; i++) line[i] = '\0';
		f.getline(line, 2048);
		game.parent = line;
		FavoritesDatabase.push_back(game);
	}

	f.close();
	return true;
}

void SaveFavorites() {
	FILE* f;
	char fileName[260];
	sprintf(fileName,"%s%s", IniPath.c_str(), "\\favorites.ini");
	f = fopen(fileName, "w+");
	if(!f) {
		//////////dprintf("SaveFavorites Error\n");
		//////////dprintf("Error opening %s\n", fileName);
		LD_LAUNCH_DASHBOARD launch;
		memset(&launch,0,sizeof(launch));
		launch.dwReason=XLD_LAUNCH_DASHBOARD_MAIN_MENU;
		XLaunchNewImage(NULL,(LAUNCH_DATA *)&launch);
	}

	if(FavoritesDatabase.size() > 0) {
		std::string e = "No Favorites Found";
		if(FavoritesDatabase[0].displayName == e) {
			fprintf(f, "%d\n", 0);
			fclose(f);
			return;
		}

		fprintf(f, "%d\n", FavoritesDatabase.size());
		for(int i = 0; i < FavoritesDatabase.size(); i++) {
			fprintf(f, "%s\n", FavoritesDatabase[i].name.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].displayName.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].date.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].manufacturer.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].system.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].genre.c_str());
			fprintf(f, "%s\n", FavoritesDatabase[i].parent.c_str());
		}
	}

	fclose(f);
}


void FavoriteSelectInput() {
	ReadInput();

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

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_B) {
		CancelSound();
		stopMovie();
		GUIState = MAIN_MENU;
		fadeOption = 0;
		fadeColor = 255;
		SaveIni();
		MenuSelected = 1;
		MenuBackground();
		m_mp3player.pause(FALSE);
		return;
	}

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

	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_UP)  {
		if(GameFavoriteSelected == 0)
			return;
		ClickSound();
		GameFavoriteSelected--; 
		if(GameFavoriteSelected < 0) 
			GameFavoriteSelected = 0;
		UpdatePreview(FavoritesDatabase[GameFavoriteSelected].name, FavoritesDatabase[GameFavoriteSelected].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 = FavoritesDatabase[GameFavoriteSelected].displayName[0];	  
			c = tolower(c);
			for(int i = GameFavoriteSelected; i > 0; i--) {
				char n = FavoritesDatabase[i].displayName[0];
				n = tolower(n);
				if(n <  c) {
					GameFavoriteSelected = i;
					UpdatePreview(FavoritesDatabase[GameFavoriteSelected].name, FavoritesDatabase[GameFavoriteSelected].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 = FavoritesDatabase[GameFavoriteSelected].displayName[0];	  
			c = tolower(c);
			for(int i = GameFavoriteSelected; i < FavoritesDatabase.size(); i++) {
				char n = FavoritesDatabase[i].displayName[0];
				n = tolower(n);
				if(n > c) {
					GameFavoriteSelected = i;
					UpdatePreview(FavoritesDatabase[GameFavoriteSelected].name, FavoritesDatabase[GameFavoriteSelected].parent);
					break;
				}
			}
			return;
	} 		

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

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

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

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

		if(((_tcscmp(FavoritesDatabase[GameFavoriteSelected].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(FavoritesDatabase[GameFavoriteSelected].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(FavoritesDatabase[GameFavoriteSelected].system.c_str(), "Cave") == 0))) {
			DisplayMessage("Please wait...");
			Device->PersistDisplay();
			XLaunchNewImage( "D:\\Cave.xbe", ldata );
		}

		if(((_tcscmp(FavoritesDatabase[GameFavoriteSelected].system.c_str(), "Toaplan GP9001 based") == 0))) {
			DisplayMessage("Please wait...");
			Device->PersistDisplay();
			XLaunchNewImage( "D:\\Toaplan.xbe", ldata );
		}	

		DisplayMessage("Please wait...");
		Device->PersistDisplay();
		XLaunchNewImage( "D:\\default.xbe", ldata );
	}

	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_WHITE) {
		if(((_tcscmp(FavoritesDatabase[0].displayName.c_str(), "No Favorites Found") == 0))) 
			return;
		RemoveFromFavorites();
		SaveFavorites();
		return;
	}

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

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

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

	if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_START) {
		ConfirmSound();
		ImageSelectedMenu((char*)FavoritesDatabase[GameFavoriteSelected].name.c_str());
	}
	if(g_Gamepads[DefaultController].wButtons & XINPUT_GAMEPAD_BACK) {
		ConfirmSound();
		char fileName[260];
		sprintf(fileName,"%s%s%s", "D:\\info\\emulation\\", FavoritesDatabase[GameFavoriteSelected].name.c_str(), ".ini");
		LoadGuide(fileName, (char*)FavoritesDatabase[GameFavoriteSelected].name.c_str());
		DrawArcadeInfo();
	}
}

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

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

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

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

		std::string t = FavoritesDatabase[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 DrawFavoriteSelectMenu() {
	DrawROMList(1);
}

void FavoriteSelectMenu() {
	DrawFavoriteSelectMenu();
	FavoriteSelectInput();
}
