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

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

// MGLinePerp2Tool

MGLinePerp2Tool::MGLinePerp2Tool(fugenDoc* pDoc)
: MGLocateState(pDoc,ID_CURVE_LINE_PERP2,NO_RUBBER,POINT_IPDRAW){
	// near が必須となる
	turn_on_near();
	turn_on_end();
}

MGLinePerp2Tool::MGLinePerp2Tool(MGCommandStateOwner* owner)
: MGLocateState(owner,UNLOCK_SNAP_ATTRIB,LINE_RUBBER,POINT_IPDRAW){
}

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

bool MGLinePerp2Tool::initiate_tool(){
	MGLocateState::initiate_tool();
	clear_pick_object();// 強制的にクリア
	return false;
}

bool MGLinePerp2Tool::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& locs=locates();
	const MGCurve& c1 = *(dynamic_cast<const MGCurve*>(locs[0]->object()));
	double t1=locs[0]->curve_parameter();
	const MGCurve& c2 = *(dynamic_cast<const MGCurve*>(locs[1]->object()));
	double t2=locs[1]->curve_parameter();

	MGPosition param(2);
	int ret = c1.perp_guess(
		1., 0.,
		c2, 1., 0., 
		t1, t2,
		param
		);

	if(!ret){
		// failed
		return MGLocateState::OnCommandEnd(2);
	}

	add_object_to_current_group(new MGStraight(c2.eval(param(1)), c1.eval(param(0))));
	return MGLocateState::OnCommandEnd(nIDS);
}

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

	// near 以外は受け付けない
	const MGCurve* curve = dynamic_cast<const MGCurve*>(info.object());
	if(!curve){
		// クリアに注意
		cancel_last_locate();
		return false;
	}

	if(locates().size()==1){
		return false;
	}

	// 評価開始
	return OnCommandEnd(1);
}

void MGLinePerp2Tool::prompt_message() const{
	switch(locates().size()){
	case 0:
		SetStatusMessage(IDS_PROMPT_POINT_ON_CURVE);
		break;
	case 1:
		SetStatusMessage(IDS_PROMPT_PERP_ANOTHER);
		break;
	}
}
