#include "fba.h"
#include "roms.h"
#include <algorithm>

CRoms::CRoms()
	{
	InitRomList();
	}

int CRoms::InitRomList()
{
 
	RomCount=0;
	RomListOK=false;

	m_vecAvailRomList.clear();
	m_vecAvailRomIndex.clear();

	return 0;
}
int CRoms::FreeRomList()
	{
	m_vecAvailRomList.clear();
	m_vecAvailRomIndex.clear();
	return 0;
	}


int CRoms::AvRoms()
	{
	RomCount=m_vecAvailRomList.size();
	return 0;
	}


int CRoms::RefreshRomList()
	{	

	// Had to rewrite this, was taking > 40 seconds to scan FBA roms in a mame 0.61
	// folder.

	std::vector<std::string> vecTempRomList;
	std::vector<std::string> vecAvailRomListFileName;
	std::vector<std::string> vecAvailRomList;
	std::vector<int>		 vecAvailRomIndex;

	char szRoms[MAX_PATH];

	strcpy((char *)szRoms, szAppRomPaths[0]);
	strcat(szRoms, "*.zip");
		
	HANDLE hFind;	
	WIN32_FIND_DATAA oFindData;

	hFind = FindFirstFile(szRoms, &oFindData);

	// Build a list of all our *.zip files first

	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			vecTempRomList.push_back(_strlwr(oFindData.cFileName));

		} while (FindNextFile(hFind, &oFindData));

	
	}
	
	FindClose(hFind);

	std::sort(vecTempRomList.begin(), vecTempRomList.end());

	int tempgame;
	tempgame = nBurnDrvSelect;
	FreeRomList();
	InitRomList();
	
	// Now build a vector of Burn Roms - all 215

	for (unsigned int i=0;i<nBurnDrvCount;i++)
		{
		nBurnDrvSelect=i;	
		char *szName;
		char *szRomName;

	 
		if (BurnDrvGetZipName(&szName, 0)) {
			break;
		}
		szRomName = (char *)malloc(strlen(szName) + strlen(szAppRomPaths[0]) + 1);
		sprintf(szRomName, "%s%s", szAppRomPaths[0], szName);
		 
		 
		vecAvailRomListFileName.push_back(szName);
		vecAvailRomList.push_back(BurnDrvText(1));
		vecAvailRomIndex.push_back(i);
		 
		}


	// For each *.zip we have, see if there is a matching burn rom
	// if so add it to the m_vec members and we are done.

	for (unsigned int x = 0; x < vecTempRomList.size(); x++)
	{

		for (unsigned int y = 0; y < vecAvailRomListFileName.size(); y++)
		{
			if (vecTempRomList[x] == vecAvailRomListFileName[y])
			{
				nBurnDrvSelect = vecAvailRomIndex[y];
				m_vecAvailRomList.push_back(BurnDrvText(1));
				m_vecAvailRomIndex.push_back(nBurnDrvSelect);
				break;
			}
			
		}

	}

	AvRoms();
	nBurnDrvSelect=tempgame;
	return 0;
	}



	
