#include"CSurfaceRenderTarget.h"
#include"CGraphic.h"
#include"../Storage/DefaultFunction/SaveImage.h"

namespace Maid
{
	
int		CSurfaceRenderTarget::s_CreateCount;

SIZE2DI		CSurfaceRenderTarget::GetSize()const
{
	MAID_ASSERT( m_ID.empty(), MAIDTEXT("まだ作成されていません") );
	return m_Size;
}

PIXELFORMAT	CSurfaceRenderTarget::GetFormat()const
{
	MAID_ASSERT( m_ID.empty(), MAIDTEXT("まだ作成されていません") );
	return m_Format;
}

mstring CSurfaceRenderTarget::GetID() const
{
	MAID_ASSERT( m_ID.empty(), MAIDTEXT("まだ作成されていません") );
	return m_ID;
}


CSurfaceRenderTarget::CSurfaceRenderTarget()
{
	m_State = STATE_EMPTY;
}

CSurfaceRenderTarget::CSurfaceRenderTarget( const CSurfaceRenderTarget& rha )
{
	if( rha.m_ID.empty() ) { return ; }

	//	本当ならサーフェス内容のコピーも必要だけど、めんどいのでしない
	Create( rha.m_Size, rha.m_Format );
}

CSurfaceRenderTarget::~CSurfaceRenderTarget()
{
	Delete();
}

CSurfaceRenderTarget& CSurfaceRenderTarget::operator = ( const CSurfaceRenderTarget& rha )
{
	Delete();
	if( rha.m_ID.empty() ) { return *this; }

	Create( rha.m_Size, rha.m_Format );

	return *this;
}

void CSurfaceRenderTarget::Create( const SIZE2DI& size, PIXELFORMAT fmt )
{
	Delete();

	const mstring id = SURFACENAME::GeneratRT( s_CreateCount );
	++s_CreateCount;

	GlobalPointer<CGraphic>::Get()->RegistSurface( id, size, fmt );

	m_ID     = id;
	m_Size   = size;
	m_Format = fmt;
	m_State  = STATE_CREATE;

}

void CSurfaceRenderTarget::Delete()
{
	if( m_ID.empty() ) { return ; }

	GlobalPointer<CGraphic>::Get()->DeleteSurface( m_ID );

	m_ID.clear();
}

void CSurfaceRenderTarget::SaveFile( const mstring& FileName )
{
	SaveFile( FileName, m_Size );
}

void CSurfaceRenderTarget::SaveFile( const mstring& FileName, const SIZE2DI& size )
{
	MAID_ASSERT( m_State!=STATE_CREATE, "まだ作られていません" );

	m_SaveFileName = FileName;
	m_SaveSize = size;

	GlobalPointer<CGraphic>::Get()->CopySurface( m_ID );

	m_State = STATE_GETSURFACE;
}

bool CSurfaceRenderTarget::IsSaving()
{
	switch( m_State )
	{
	case STATE_EMPTY:
	case STATE_CREATE: { return false; }break;

	case STATE_GETSURFACE:
		{
			const bool IsOK = GlobalPointer<CGraphic>::Get()->IsCopySurfaceEnd( m_ID );

			if( IsOK )
			{
				SPSURFACEBUFFER pSurf = GlobalPointer<CGraphic>::Get()->GetCopySurface( m_ID );

				boost::shared_ptr<SaveImageFunction> pParam( new SaveImageFunction );

				pParam->pSurface = pSurf;
				pParam->SaveSize = m_SaveSize;

				const int id =  GlobalPointer<CStorageCore>::Get()->Execute( StorageDefaultFunction::SAVESURFACE, m_SaveFileName, pParam );

				m_TickeID  = id;
				m_State = STATE_SAVESURFACE;
			}
		
		}break;

	case STATE_SAVESURFACE:
		{
			CStorageCore* pStorage = GlobalPointer<CStorageCore>::Get();

			if( pStorage->IsNowLoading( m_TickeID ) ) { return true; }

			pStorage->GetReturnParam( m_TickeID );
			m_State = STATE_CREATE;
		}break;
	}
	return true;
}

}

