#include "stdafx.h"
#include "mg/LBRep.h"
#include "Calc/curve.h"
#include "Calc/mgcalc.h"
#include "GLInputNumberDlg.h"
#include "fugenView.h"
#include "Misc/UserPreference.h"
#include "CurveCmd/SplineBezierCurveTool.h"

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

// MGSplineBezierCurveTool

MGSplineBezierCurveTool::MGSplineBezierCurveTool(fugenDoc* pDoc)
: MGLocateState(pDoc,ID_CURVE_SPLINE_BEZIER,LINE_RUBBER,POINTLINE_IPDRAW)
,m_nIDS(1), m_curve(new MGLBRep){
}

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

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

bool MGSplineBezierCurveTool::terminate_tool(bool cancel){
	return MGLocateState::terminate_tool(cancel);
}

bool MGSplineBezierCurveTool::calculate(){
	const LInfoVec& linfos=locates();
	if(linfos.size()<=1){
		// cancel扱い
		m_nIDS = 1;
		return false;
	}

	std::vector<MGPosition> iposes;
	extract_points_world(linfos,iposes);
	int n=(int)iposes.size();
	int k=n>=4 ? 4:n;
	MGKnotVector t(k, n, 0., 1.);
	MGBPointSeq bp(iposes);
	m_curve->buildLBRepFromMemberData(std::move(t),std::move(bp));

	// ドキュメントを変更
	add_object_to_current_group(m_curve.release());

	return true;
}

void MGSplineBezierCurveTool::do_make_temporary_display(mgSysGL& sgl,fugenView* pView){
	const LInfoVec& linfos=locates();
	if(locates().size()>=2){
		std::vector<MGPosition> iposes;
		extract_points_world(linfos,iposes);
		iposes.push_back(cursor());
		int n=(int)iposes.size();
		int k=n>=4 ? 4:n;
		MGKnotVector t(k, n, 0., 1.);
		MGBPointSeq bp(iposes);
		m_curve->buildLBRepFromMemberData(std::move(t), std::move(bp));

		if(m_curve.get()){
			MGColor::get_instance(MGColor::SpringGreen).exec(sgl);
			m_curve->drawWire(sgl);
		}
	}
}

bool MGSplineBezierCurveTool::OnKeyDown(fugenView* pView, UINT nChar, UINT nRepCnt, UINT nFlags){	
	return MGLocateState::OnKeyDown(pView, nChar, nRepCnt, nFlags);
}

bool MGSplineBezierCurveTool::OnLocated(const MGLocateInfo& info){
	if (locates().size()==4){
		return calculate() ? OnCommandEnd(1) : OnCommandEnd(m_nIDS);
	} else {
		return false;
	}
}

void MGSplineBezierCurveTool::prompt_message() const{
	switch(locates().size()){
	case 0:
		SetStatusMessage(IDS_PROMPT_CURVE_BEZIER_0);
		break;
	case 1:
	case 2:
		SetStatusMessage(IDS_PROMPT_CURVE_BEZIER_1);
		break;
	default:
		SetStatusMessage(IDS_PROMPT_CURVE_BEZIER);
		break;
	}
}
