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

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

// MGPointEndTool

MGPointEndTool::MGPointEndTool(fugenDoc* pDoc, bool bExtractStart)
	 : MGSelectState(
		 pDoc,
		 ID_CURVE_START_POINT,
		 MGSelectState::MULTIPLE_SELECT,
		 mgAll_Curve
		 ),
	   m_nIDS(1),
	   m_bExtractStart(bExtractStart)
{
	if(!m_bExtractStart){
		set_command_id(ID_CURVE_END_POINT);
	}
}

MGCommandBase* MGPointEndTool::initial_clone(fugenDoc* pDoc) const
{
	// 他のクラスと若干異なる
	return new MGPointEndTool(pDoc, m_bExtractStart);
}

bool MGPointEndTool::initiate_tool(){
	MGSelectState::initiate_tool();
	if(current_object_is_valid(mgAll_Curve,m_curve)){
		set_current_object(m_curve);
		UINT id = calculate() ? 1:m_nIDS;
		return OnCommandEnd(id);
	}else{
		set_add_mode();
		prompt_message();
	}
	return false;
}

bool MGPointEndTool::calculate(){
	if(m_curve.empty()){
		// キャンセル
		return false;
	}

	SetStatusMessage(IDS_PROMPT_COMPUTE);
	CWaitCursor hourglass;

	// 計算開始
	fugenView* glw=get_main_view();
	MGGroup* root = &(document()->get_main_group(glw));
	//MGGroup* root = doc_root();
	MGGelPositions gelps;

	MGPickObjects& curobj = m_curve;
	MGPickObjects::const_iterator
		first = curobj.begin(), last = curobj.end();
	for(; first != last; ++first){
		const MGCurve* pCurve = dynamic_cast<const MGCurve*>((*first)->top_object());
		if(!pCurve || pCurve->is_closed()){
			continue;
		}
		std::unique_ptr<MGPoint> spPt(new MGPoint(
			m_bExtractStart ? pCurve->start_point() : pCurve->end_point()));
		gelps.push_back(MGGelPosition(root,spPt.release()));
	}

	if(gelps.empty()){
		// failed
		m_nIDS = IDS_FAIL_GENERATE_POINT;
		return false;
	}

	// ドキュメントを変更
	add_object_to_document(gelps);
	return true;
}

bool MGPointEndTool::OnKeyDown(fugenView* pView, UINT nChar, UINT nRepCnt, UINT nFlags){
	switch(nChar){
	case VK_RETURN:
		m_curve = current_objects();
		if(m_curve.empty()){
			return false;
		}
		
		if(!calculate()){
			return OnCommandEnd(m_nIDS);
		}
		return OnCommandEnd(1);
	default:
		return MGSelectState::OnKeyDown(pView, nChar, nRepCnt, nFlags);
	}
}

void MGPointEndTool::prompt_message() const{
	SetStatusMessage(IDS_PROMPT_CURVE);
}

// ファクトリーで使用する。

MGCommandBase* CreatePointEndTool(fugenDoc* pDoc, UINT nCmdId)
{
	if(nCmdId == ID_CURVE_START_POINT){
		return new MGPointEndTool(pDoc, true);
	}
	else if(nCmdId == ID_CURVE_END_POINT){
		return new MGPointEndTool(pDoc, false);
	}
	return 0;
}
