#include "stdafx.h"
#include "2DObject.h"

/************************************************************************
 二维图幅类
************************************************************************/
C2DMap::C2DMap()
{
	m_arObj.RemoveAll();
}

C2DMap::~C2DMap()
{
	int nCount = (int)m_arObj.GetCount();
	C2DObject* pObj = NULL;
	for (int i=0; i!=nCount; ++i)
	{
		pObj = m_arObj.GetAt(i);
		delete pObj;
        pObj =NULL;
	}
	m_arObj.RemoveAll();
	m_arObj.FreeExtra();
}

void C2DMap::Serialize( CFile* pFile, BOOL bSave /*= TRUE */ )
{
	if (bSave)
	{
		C2DObject *pObj = NULL;
		int nCount = (int)m_arObj.GetCount();
		UINT wClassType = 0;
		pFile->Write(&nCount,sizeof(int));
		for (int i=0; i!=nCount; ++i)
		{
			pObj = m_arObj.GetAt(i);
			wClassType = pObj->GetClass();
			pFile->Write(&wClassType,sizeof(UINT));
			pObj->Serialize(pFile, bSave);
		}
	} 
	else
	{
		m_arObj.RemoveAll();
		m_arObj.FreeExtra();
		C2DObject *pObj = NULL;
		int nCount = 0;
		pFile->Read(&nCount,sizeof(int));
		UINT wClassType = 0;
		for (int i=0; i!=nCount; ++i)
		{
			pFile->Read(&wClassType,sizeof(UINT));
			pObj = C2DObject::CreateObject((enum enumDrawClass)wClassType);
			if (pObj)
			{
				pObj->Serialize(pFile, bSave);
				m_arObj.Add(pObj);
			}
			else
			{
				TRACE("Warning: 不能识别的对象类型，在C2DMap::Serialize");
			}
		}
	}
}

int C2DMap::AddObject( C2DObject* pObj )
{
	if (pObj==NULL)
	{
		return -1;
	}
    return (int)m_arObj.Add(pObj);
}

void C2DMap::Draw( CDC* pDC )
{
	int nCount = (int)m_arObj.GetCount();
	for (int i=0; i!=nCount; ++i)
	{
		C2DObject* pObj = m_arObj.GetAt(i);
		pObj->Draw(pDC);
	}
}

BOOL C2DMap::Save( CString szFilePath )
{
	CFile file;
	if (!file.Open(szFilePath, CFile::modeCreate|CFile::modeWrite))
	{
		AfxMessageBox(_T("不能写入该文件！"));
		return FALSE;
	}

	TRY 
	{
		CString szMark = _T("Sivan - Draw2D");
		file.Write((const char*)szMark,szMark.GetLength());
		g_2DObj.Serialize(&file, TRUE);
		Serialize(&file, TRUE);
		file.Close();
	}
	CATCH (CFileException, e)
	{
		AfxMessageBox(_T("写文件出错！"));
		file.Close();
		return FALSE;
	}
	END_CATCH

	return TRUE;
}

void C2DMap::Open( CString szFilePath )
{
	CFile file;
	if (!file.Open(szFilePath, CFile::modeRead))
	{
		AfxMessageBox(_T("不能打开此文件！"));
		return;
	}

	TRY 
	{
		char szMark[15];
		file.Read(szMark, 14);
		szMark[14] = '\0';
		if (strcmp(szMark, _T("Sivan - Draw2D"))!=0)
		{
			file.Close();
			return;
		}
		g_2DObj.Serialize(&file, FALSE);
		Serialize(&file, FALSE);
		file.Close();
	}
	CATCH (CFileException, e)
	{
		AfxMessageBox(_T("读文件出错C2DMap::Open!"));
		file.Close();
		return;
	}
	END_CATCH
 
	return;
}

DWORD C2DMap::GetCount()
{
	return (DWORD)m_arObj.GetCount();
}