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

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

// MGCurveIsectTool

MGCurveIsectTool::MGCurveIsectTool(fugenDoc* pDoc)
	 : MGSelectState(
		 pDoc,
		 ID_CURVE_INTERSECTION,
		 MGSelectState::MULTIPLE_SELECT
		 ),
	   m_nIDS(1)
{
}

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

bool MGCurveIsectTool::initiate_tool(){
	MGSelectState::initiate_tool();
	
	const MGPickObjects& curobj = current_objects();
	if(curobj.size() >= 2){
		if(!calculate()){
			// failed
			return OnCommandEnd(m_nIDS);
		}
		return OnCommandEnd(1);
	}
	set_add_mode();
	lock_so_far();
	prompt_message();
	return false;
}

bool MGCurveIsectTool::OnKeyDown(fugenView* pView, UINT nChar, UINT nRepCnt, UINT nFlags){
	switch(nChar){
	case VK_RETURN:{
			const MGPickObjects& curobj = current_objects();
			if(curobj.size()>=2){
				// 交線計算開始
				if(!calculate()){
					// failed
					return OnCommandEnd(m_nIDS);
				}
				return OnCommandEnd(1);
			}
		}
		break;
	default:;
	}
	return MGSelectState::OnKeyDown(pView, nChar, nRepCnt, nFlags);
}

bool MGCurveIsectTool::calculate(){
	const MGPickObjects& curobj = current_objects();
	if(curobj.size() < 2){
		// cancel?
		OnCommandEnd(m_nIDS);
		return false;
	}
	
	SetStatusMessage(IDS_PROMPT_COMPUTE);
	CWaitCursor sandglass;

	MGisects res;
	MGPickObjects::const_iterator first1 = curobj.begin(), last = curobj.end(), first2;
	for(; first1 != last; ++first1){
		first2 = first1;
		++first2;
		for(; first2 != last; ++first2)
			res.push_back((*first1)->top_object()->isect(*((*first2)->top_object())));
	}
	
	if(res.empty()){
		// failed
		m_nIDS = IDS_FAIL_GENERATE_CURVE;
		return false;
	}
	
	// 3. ドキュメント変更
	//Conversion to MGGelPositions from MGisects.
	MGGroup* grp=current_group();
	MGGelPositions gpos;
	MGisects::const_iterator i=res.begin(), ie=res.end();
	for(; i!=ie; i++)
		gpos.push_back(MGGelPosition(grp,(*i)->isect().clone()));
	add_object_to_document(gpos);
	return true;
}

void MGCurveIsectTool::prompt_message() const{
	SetStatusMessage(IDS_PROMPT_SURFACE);
}
