#include "PatchInfoList.h"
#include "PatchInfoListV1.h"


const char* CPatchInfoList::ms_cszHeaderString = "PAT2";



//////////////////////////////////////////////////////////////////////////
//
bool CPatchInfoList::Load( const char* szFileName )
{
	FILE* fp = fopen(szFileName, "rb");
	
	if( NULL == fp )
	{
		return false;
	}
	
	// check header
	char acTmp[4] = { 0, };
	fread( acTmp, 4, sizeof(char), fp );
	if( acTmp[0] != ms_cszHeaderString[0] ||
		acTmp[1] != ms_cszHeaderString[1] ||
		acTmp[2] != ms_cszHeaderString[2] ||
		acTmp[3] != ms_cszHeaderString[3]
		)
	{
		fclose(fp);
		return false;
	}
	
	// read version
	fread( &m_dwVersion, sizeof(DWORD), 1, fp );
	
	// read count
	long lCount;
	fread( &lCount, sizeof(long), 1, fp );
	
	// read data
	m_vecPatchInfo.resize( lCount );
	
	if( lCount !=
		(long)fread( &(m_vecPatchInfo[0]), sizeof(FilePatchInfoRecord), lCount, fp ) )
	{
		fclose(fp);
		return false;
	}
	
	FilePatchInfoRecord info = m_vecPatchInfo[0];
	
	fclose(fp);
	return true;
}


bool CPatchInfoList::Save( const char* szFileName )
{
	FILE* fp = fopen(szFileName, "wb");
	
	if( NULL == fp )
	{
		return false;
	}
	
	// write header
	fwrite( ms_cszHeaderString, 4, sizeof(char), fp );
	
	// write version
	fwrite( &m_dwVersion, sizeof(DWORD), 1, fp );
	
	// write count
	long lCount = m_vecPatchInfo.size();
	fwrite( &lCount, sizeof(long), 1, fp );
	
	// write data
	fwrite( &(m_vecPatchInfo[0]), sizeof(FilePatchInfoRecord), lCount, fp );
	
	
	fclose(fp);
	return true;
}


void CPatchInfoList::Reset()
{
	m_dwVersion = 0;
	m_vecPatchInfo.clear();
}


bool CPatchInfoList::LoadV1( const char* szFileName )
{
	FILE* fp = fopen(szFileName, "rb");
	
	if( NULL == fp )
	{
		return false;
	}
	
	// check header
	char acTmp[4] = { 0, };
	fread( acTmp, 4, sizeof(char), fp );
	if( acTmp[0] != 'P' ||
		acTmp[1] != 'A' ||
		acTmp[2] != 'T' ||
		acTmp[3] != '1'
		)
	{
		fclose(fp);
		return false;
	}
	
	// read version
	fread( &m_dwVersion, sizeof(DWORD), 1, fp );
	
	// read count
	long lCount;
	fread( &lCount, sizeof(long), 1, fp );
	
	// read data
	std::vector< FilePatchInfoRecordV1 > vecV1;

	vecV1.resize( lCount );

	if( lCount !=
		(long)fread( &(vecV1[0]), sizeof(FilePatchInfoRecordV1), lCount, fp ) )
	{
		fclose(fp);
		return false;
	}
	
	fclose(fp);

	m_vecPatchInfo.resize( lCount );

	for( int i = 0; i < lCount; ++i )
	{
		strcpy( m_vecPatchInfo[i].szFileName, vecV1[i].szFileName );
		strcpy( m_vecPatchInfo[i].szPackageFileName, vecV1[i].szPackageFileName );
		m_vecPatchInfo[i].dwCRC32 = vecV1[i].dwCRC32;
		m_vecPatchInfo[i].dwSize = vecV1[i].dwSize;

		//m_vecPatchInfo[i].dwVersion = 100;
		m_vecPatchInfo[i].dwVersion = m_dwVersion;
	}

	vecV1.clear();
	
	return true;
}
