/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/* ***************************************************** */
/********************************************************************/
#include "stdafx.h"
#include "mgGL/OpenGLView.h"
#include "mgGL/glViewAttrib.h"
#include "Undo/CameraAction.h"
#include "Undo/ICameraActionTarget.h"
#include "Undo/IActionManager.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

CCameraAction::CCameraAction(ICameraActionTarget* pView)
: CActionBase(pView){
}

CCameraAction::~CCameraAction(){
}

void CCameraAction::Do(){
	SetLastAction();

	ICameraActionTarget* pView = GetTargetView();
	if(pView && m_spEnvNew.get()){
		pView->GetCamera().copy(*m_spEnvNew);
		pView->Refresh();
	}
	GetActionTarget()->SetDirtyFlag();
}

void CCameraAction::Redo(){
	CActionBase::Redo();

	ICameraActionTarget* pView = GetTargetView();
	if(pView && m_spEnvNew.get()){
		pView->GetCamera().copy(*m_spEnvNew);
		pView->Refresh();
	}
	GetActionTarget()->SetDirtyFlag();
}

void CCameraAction::Undo(){
	ICameraActionTarget* pView = GetTargetView();
	if(pView && m_spEnvOld.get()){
		pView->GetCamera().copy(*m_spEnvOld);
		pView->Refresh();
	}
	CActionBase::Undo();
}

ICameraActionTarget* CCameraAction::GetTargetView(){
	return static_cast<ICameraActionTarget*>(GetActionTarget());
}

const MGglViewAttrib* CCameraAction::GetEnvParam(ACTION_TYPE actiontype)const{
	if(actiontype == ACTION_UNDO){
		return m_spEnvOld.get();
	}else{
		return m_spEnvNew.get();
	}
}

void CCameraAction::SaveEnvParam(ACTION_TYPE actiontype){
	ICameraActionTarget* pView = GetTargetView();
	ASSERT(pView);

	std::unique_ptr<MGglViewAttrib> spEnv(new MGglViewAttrib);

	// この時点での MGOpenGLView に入っているパラメータをキープ。
	*spEnv=pView->GetCamera().viewAttrib();

	if(actiontype == ACTION_UNDO){
		m_spEnvOld = std::move(spEnv);
	}else{
		m_spEnvNew = std::move(spEnv);
	}
}

void CCameraAction::SetLastAction(){
	if(IsAutoNotify()){
		ICameraActionTarget* pTarg = static_cast<ICameraActionTarget*>(GetActionTarget());
		IActionManager* pMgr = pTarg->GetCameraActionManager();
		pMgr->SetLastAction(this);
	}
}
