/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/drivers/wintel32/filesystem/win32memcarddevice.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/filesystem/filesystem.hpp"
#include "drivers/wintel32/device.hpp"
#include "drivers/wintel32/filesystem/filesystem.hpp"

CSGXDeviceBlockStateWin32MemoryCard::CSGXDeviceBlockStateWin32MemoryCard(CSGXDeviceMemoryCard *pDevice, CSGXDeviceBlockMemoryCard *pBlock, const tBOOL bSaving) :
	CSGXDeviceMemoryCardFile(pDevice, pBlock, bSaving) {

	if (!bSaving) {
		DWORD bytesread;
        HANDLE hFile = ::CreateFile(pBlock->m_Filename.c_str(), FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		::ReadFile(hFile, m_pData, m_iSize, &bytesread, NULL);
		::CloseHandle(hFile);
	}
}

CSGXDeviceBlockState *CSGXDeviceWin32MemoryCard::open(CSGXDeviceBlock *pBlk, const sgxString &access)
{
	CSGXDeviceBlockMemoryCard *pBlock = SGX_STATIC_CAST(CSGXDeviceBlockMemoryCard *, pBlk);
	CSGXDeviceBlockStateWin32MemoryCard *pState = new CSGXDeviceBlockStateWin32MemoryCard(this, pBlock, (access == "rw")?TRUE:FALSE);
	return pState;
}

tBOOL CSGXDeviceWin32MemoryCard::mountDirectory(CSGXFileEntry *pEntry, const sgxString &rootmount, tBOOL recursive) {
SGX_UNUSED(rootmount);
SGX_UNUSED(recursive);

	sgxString s;
	WIN32_FILE_ATTRIBUTE_DATA info;
	for(tUINT32 i=0;i<4;++i) {
		sgxStringFormat(s, "memcard%d",i);
		if (GetFileAttributesEx(s.c_str(), GetFileExInfoStandard, &info) != 0) {
			CSGXFileSysData data(rootmount+"/"+s);
			data.m_Filesize = info.nFileSizeLow;
			CSGXDeviceWin32Disc::getFileModifiedDate(data.m_LastModifiedDate, info.ftLastWriteTime);
			CSGXFileSystem::get()->addNewFile(data);
		}
	}

    return TRUE;
}
