/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/
/********************************************************************/
// RotateTool.cpp: MGViewRotateTool クラスのインプリメンテーション

#include "stdafx.h"
#include "ViewCmd/ViewRotateTool.h"
#include "Undo/CameraAction.h"
#include "fugenView.h"

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

// MGViewRotateTool

MGViewRotateTool::MGViewRotateTool(fugenDoc* pDoc)
	 : MGCommandBase(pDoc, ID_VIEW_ROTATE),
	   m_hCursor(0),
	   m_bTracking(false)
{
}

MGCommandBase* MGViewRotateTool::initial_clone(fugenDoc* pDoc) const
{
	return new MGViewRotateTool(pDoc);
}

bool MGViewRotateTool::initiate_tool(){
	MGCommandBase::initiate_tool();

	VERIFY(m_hCursor = AfxGetApp()->LoadCursor(IDC_CURSOR_ROTATE));
	SetStatusMessage(IDS_PROMPT_VIEW_ROTATE);
	return false;
}

bool MGViewRotateTool::terminate_tool(bool cancel)
{
	if(m_spAction.get()){
		m_spAction.reset();
	}
	m_bTracking = false;
	return MGCommandBase::terminate_tool(cancel);
}

bool MGViewRotateTool::OnLButtonDown(fugenView* pView, UINT, CPoint point)
{
	m_bTracking = true;

	// 開始直後のカメラの状態を保存。
	// Memento パターンで言うところの createMemento 操作。
	m_spAction.reset(new CCameraAction(pView));
	m_spAction->SaveEnvParam(IAction::ACTION_UNDO);

	SetStatusMessage(IDS_PROMPT_VIEW_ROTATE);
	return false;
}

bool MGViewRotateTool::OnLButtonUp(fugenView* pView, CPoint, UINT, CPoint point)
{
	if(m_bTracking){
		// カメラ操作終了直後とみなして、最終カメラ状態を保存。
		m_spAction->Do(); // 先に Do() して、SetLastAction のみを実行させる。
		m_spAction->SaveEnvParam(IAction::ACTION_REDO);

		// アクションの所有権を ActionManager に委ねる。
		m_spAction.release();

		m_bTracking = false;
		::ReleaseCapture();
	}
	return OnCommandEnd(1);
}

bool MGViewRotateTool::OnMouseMove(fugenView* pView, UINT nFlags, CPoint point)
{
	if(m_bTracking){
		pView->SetCapture();
		pView->mouse_move_transform(point);
		pView->redrawOnlythis();
	}
	return false;
}

bool MGViewRotateTool::OnSetCursor(
	fugenView* pView,
	CWnd* pWnd,
	UINT nHitTest,
	UINT message)
{
	if(m_bTracking && m_hCursor){
		::SetCursor(m_hCursor);
		return true;
	}

	// 基底クラスの OnSetCursor に任せる。
	return MGCommandBase::OnSetCursor(pView, pWnd, nHitTest, message);
}
