/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/* ***************************************************** */
/********************************************************************/
/**
 * @file CornerR_CCPTool.cpp
 * @brief MGCornerR_CCPTool クラスのインプリメンテーション
 */
#include "stdafx.h"
#include "fugenDoc.h"
#include "fugenView.h"
#include "CurveCmd/CornerR_CCPTool.h"
#include "mg/Ellipse.h"

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

// MGCornerR_CCPTool

MGCornerR_CCPTool::MGCornerR_CCPTool(fugenDoc* pDoc)
: MGLocateState(pDoc,ID_CURVE_CORNER_R_CCP,NO_RUBBER,POINT_IPDRAW){
	turn_on_near();
	turn_on_end();
}

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

bool MGCornerR_CCPTool::initiate_tool(){
	MGLocateState::initiate_tool();
	clear_pick_object();
	return false;
}

bool MGCornerR_CCPTool::OnCommandEnd(
	UINT nIDS,	//=0: erase the current message, and display no messages.
			//=1: display "xxxx" normally end.
			//otherwise: nIDS is a string id, and load the message from string table to display.
	bool erase_temporary_display
){
	const LInfoVec& linfos=locates();
	if(linfos.size()<2)
		return MGLocateState::OnCommandEnd(3);

	// 計算開始
	SetStatusMessage(IDS_PROMPT_COMPUTE);
	CWaitCursor sandglass;

	const MGCurve& c1=*(dynamic_cast<const MGCurve*>(linfos[0]->object()));
	double t1=linfos[0]->curve_parameter();
	const MGCurve& c2=*(dynamic_cast<const MGCurve*>(linfos[1]->object()));
	double t2=linfos[1]->curve_parameter();

	// ノーマルを計算してみる
	MGPosition pos1 = c1.eval(t1);
	MGPosition pos2 = c2.eval(t2);
	MGVector v1 = c1.eval(t1, 1); // 1次微分

	int ret = 0;
	double tmp = 0.;
	std::unique_ptr<MGEllipse> arc(new MGEllipse(c1,c2,v1*(pos2-pos1),t1,t2,ret));
	if(ret){
		// failed
		return MGLocateState::OnCommandEnd(IDS_FAIL_GENERATE_CURVE);
	}

	add_object_to_current_group(arc.release());
	return MGLocateState::OnCommandEnd(nIDS);
}

bool MGCornerR_CCPTool::OnLocated(const MGLocateInfo& info){
	if(info.is_deleted()){
		return false;
	}

	const MGCurve* curve = dynamic_cast<const MGCurve*>(info.object());
	if(!curve){
		// 曲線上の点以外のクリックは認めない
		cancel_last_locate();
		return false;
	}

	LInfoVec& linfos=locates();
	if(linfos.size()>=2){
		const MGCurve* c1=dynamic_cast<const MGCurve*>(linfos[0]->object());
		if(c1==curve)
			cancel_last_locate();
	}

	if(linfos.size()<2){
		return false;
	}

	// 計算開始
	return OnCommandEnd(1);
}

void MGCornerR_CCPTool::prompt_message() const{
	if(locates().size()==0){
		SetStatusMessage(IDS_PROMPT_CORNER_R_START);
	}else{
		SetStatusMessage(IDS_PROMPT_CIRCLE_BASELINE, 2);
	}
}
