#include "GlobalExtern.h"

void DrawSkinMenu() {
	int y = MenuPosY;
	DWORD color;
	int start = 0;
	if(SkinSelected > 7 && (Skin.size() > 15)) {
		start += (SkinSelected  - 7);
	}
	if((SkinSelected > ((Skin.size()-1) - 7)) && (Skin.size() > 15)) {
		start = (Skin.size() - 15);
	}
	for(int i = start; i <  start +15; i++) {
		if(i == Skin.size()) return;
		if(i == SkinSelected) color = 0xffff00; else color = 0xffffff; 
		WCHAR msg[1024]={0};
		std::string t = Skin[i];
		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);
		FontCenteredText(msg, MenuPosX, y, 600);
		y+=vSpace;
	}
}

bool SkinMenuInput() {
	ReadInput();
	if(g_Gamepads[0].Event == XBGAMEPAD_B) {
		CancelSound();
		return false;          
	} 
	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_DOWN)  {
		ClickSound();
		SkinSelected++; 
		if(SkinSelected >= Skin.size()) 
			SkinSelected = Skin.size() - 1;
		return true;
	}
	if (g_Gamepads[DefaultController].Event == XBGAMEPAD_DPAD_UP)  {
		ClickSound();
		SkinSelected--; 
		if(SkinSelected < 0) 
			SkinSelected = 0;
		return true;
	}  
	if(g_Gamepads[DefaultController].Event == XBGAMEPAD_A) {
		LoadSkinIni(Skin[SkinSelected]);
		GUIState = 0;
		SaveIni();
		//Device->PersistDisplay();
		PLAUNCH_DATA ldata ;
		memset( &ldata, 0, sizeof(PLAUNCH_DATA) ) ;
		XLaunchNewImage( "D:\\default.xbe", ldata ) ;
	}

	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER]) {
		if(analogSpeed >= 1) { 
			analogSpeed = 0; 
		} 
		if(rightAnalog == 255)
			analogSpeed = scrollSpeed;
		else
			analogSpeed += ((float)rightAnalog/255.0f);
		SkinSelected+=((int)analogSpeed); 
		if(SkinSelected >= Skin.size()) 
			SkinSelected = Skin.size() - 1;
		return true;
	}
	if( g_Gamepads[DefaultController].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER]) {
		if(analogSpeed >= 1)  { 
			analogSpeed = 0;
		}
		if(leftAnalog == 255)
			analogSpeed = scrollSpeed;
		else
			analogSpeed += ((float)leftAnalog/255.0f);
		SkinSelected-=((int)analogSpeed); if(SkinSelected < 0) SkinSelected = 0;
		return true;
	}
	return true;
}

void BuildSkins() {
	Skin.clear();

	HANDLE find=NULL;
	WIN32_FIND_DATA wfd;
	memset(&wfd,0,sizeof(wfd));

	find=FindFirstFile("D:\\skins\\*",&wfd);

	if (find==INVALID_HANDLE_VALUE)return;

	for (;;)
	{
		if((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
		   std::string t1(wfd.cFileName);
		   Skin.push_back(t1);
		}
		if (FindNextFile(find,&wfd)==0) break;
	}
	sort(Skin.begin(), Skin.end());
	FindClose(find);
}