#include "stdafx.h"
#include "ImageFileManager.h"
#include <io.h>

CImageFileManager::CImageFileManager()
{
	m_lImageIdx = 1;
}


CImageFileManager::~CImageFileManager()
{
	Clear();
}
long  CImageFileManager::AddFile(CString strFileName)
{
	if (0x00 != _taccess(strFileName, 0x00))
	{
		return -1;
	}
	CxImage _img;
	if (FALSE == _img.Load(strFileName.GetBuffer()))
	{
		strFileName.ReleaseBuffer();
		return -1;
	}
	strFileName.ReleaseBuffer();
	 

	CFile _file;
	if (FALSE == _file.Open(strFileName, CFile::modeRead|CFile::typeBinary))
		return -1;

	stFileInfo* pFileInfo = new stFileInfo();
	pFileInfo->strFileName = strFileName;
	pFileInfo->lImageBufferLength = _file.GetLength() + 1;
	pFileInfo->pImageBuffer = new BYTE[pFileInfo->lImageBufferLength];
	memset(pFileInfo->pImageBuffer, 0x00, pFileInfo->lImageBufferLength);
	
	_file.Read(pFileInfo->pImageBuffer, _file.GetLength());

	_file.Close();

	pFileInfo->lImageIdx = m_lImageIdx;
	pFileInfo->nImageWidth = _img.GetWidth();
	pFileInfo->nImageHeight = _img.GetHeight();
	m_fileInfo.Add(pFileInfo);
 
	 
	m_lImageIdx++;

	return pFileInfo->lImageIdx;
	
}
CImageFileManager::stFileInfo* CImageFileManager::GetFileByIdx(long lIdx)
{
	for (int i = 0; i < m_fileInfo.GetSize(); i++)
	{
		stFileInfo* pFileInfo = m_fileInfo.GetAt(i);
		if (pFileInfo->lImageIdx == lIdx)
		{
			return pFileInfo;
		}
	}
	return NULL;
}
void  CImageFileManager::DeleteFile(long lImageIdx)
{
	for (int i = 0; i < m_fileInfo.GetSize(); i++)
	{
		stFileInfo* pFileInfo = m_fileInfo.GetAt(i);
		if (pFileInfo->lImageIdx == lImageIdx)
		{
			if (pFileInfo->pImageBuffer != NULL)
			{
				delete[] pFileInfo->pImageBuffer;
			}
			delete pFileInfo;

			m_fileInfo.RemoveAt(i);
			break;
		}
	}
}
void  CImageFileManager::GetAllFileInfo(CArray<CImageFileManager::stFileInfo*, CImageFileManager::stFileInfo*>& _out)
{
	_out.Copy(m_fileInfo);
}
void  CImageFileManager::Clear()
{
	for (int i = 0; i < m_fileInfo.GetSize(); i++)
	{
		stFileInfo* pFileInfo = m_fileInfo.GetAt(i);

		if (pFileInfo->pImageBuffer != NULL)
		{
			delete[] pFileInfo->pImageBuffer;
		}
		delete pFileInfo;
	}
	m_fileInfo.RemoveAll();
}