#include"CSoundFileStream.h"
#include"../Storage/Core/CStorageCore.h"
#include"../Auxiliary/CString.h"

#include"../Storage/FunctionEnum.h"
#include"../Storage/DefaultFunction/LoadSound.h"

namespace Maid
{

CSoundFileStream::CSoundFileStream()  
	:m_State(STATE_EMPTY)
{
}

CSoundFileStream::CSoundFileStream( const CSoundFileStream& rha )
	:m_State(STATE_EMPTY)
{
	if( rha.m_State == STATE_EMPTY ) { return ; }

	Load( rha.GetFileName() );
}

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

CSoundFileStream& CSoundFileStream::operator = ( const CSoundFileStream& rha )
{
	Delete();

	if( rha.m_State != STATE_EMPTY )
	{
		Load( rha.GetFileName() );
	}

	return *this;
}

void CSoundFileStream::Load( const mstring& FileName )
{
	const int id =  GlobalPointer<CStorageCore>::Get()->Execute( StorageDefaultFunction::LOADSOUNDSTREAM, FileName, SPSTORAGEFUNCTION_FUNCTIONPARAM() );

	m_TickeID  = id;
	m_State    = STATE_LOADING;
	m_FileName = FileName;
}

void CSoundFileStream::Delete()
{
	switch( m_State )
	{
	case STATE_EMPTY:
		{

		}break;

	case STATE_LOADING:
		{
			GlobalPointer<CStorageCore>::Get()->Cancel( m_TickeID );
		}break;

	case STATE_WORKING:
		{
			m_pObject.reset();
		}break;
	}

	m_TickeID  = -1;
	m_State    = STATE_EMPTY;
	m_FileName.clear();
}

mstring CSoundFileStream::GetFileName() const
{
	MAID_ASSERT( m_State==STATE_EMPTY, "まだ読み込んでいません" );
	return m_FileName;
}

bool CSoundFileStream::IsNowLoading()
{
	MAID_ASSERT( m_State==STATE_EMPTY, "まだ読み込んでいません" );

	if( m_State==STATE_WORKING ) { return false; }


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

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

	//	ここまできたら終わっているので更新作業
	{
		SPSTORAGEFUNCTION_RETURNPARAM pParam = pStorage->GetReturnParam( m_TickeID );
		LoadSoundStreamReturn* p = static_cast<LoadSoundStreamReturn*>(pParam.get());

		m_pObject.reset( new CSoundObjectCore );
		m_pObject->LoadPCMStream( p->pDecoder );
	}

	m_State = STATE_WORKING;
	return false;
}

SPSOUNDOBJECTCORE	CSoundFileStream::GetSoundObjectCore()
{
	return m_pObject;
}


}