/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/

// SnapPointGenTool.cpp: MGSnapPointGenTool クラスのインプリメンテーション

#include "stdafx.h"
#include "mgGL/SnapPositions.h"
#include "fugenDoc.h"
#include "EvalCmd/SnapPointGenTool.h"

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

// MGSnapPointGenTool

MGSnapPointGenTool::MGSnapPointGenTool(fugenDoc* pDoc)
: MGSelectState(pDoc, ID_EVAL_SNAP_GEN, MGSelectState::MULTIPLE_SELECT){
}

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

bool MGSnapPointGenTool::initiate_tool(){
	MGSelectState::initiate_tool();
	if(!current_objects().empty()){
		// いきなり計算
		return OnCommandEnd(1);
	}
	// 最初のメッセージ
	SetStatusMessage(IDS_PROMPT_OBJECT);
	return false;
}

bool MGSnapPointGenTool::input_param(){
	SetStatusMessage(IDS_PROMPT_SNAP_EVAL);
	return IDOK == m_dlg.DoModal();
}

bool MGSnapPointGenTool::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 MGPickObjects& picked = current_objects();
	if(picked.empty()){
		// cancel
		return MGSelectState::OnCommandEnd(3);
	}

	MGPickObjects curves;
	picked.select_curves(curves);
	m_dlg.m_TargetKind=0;
	if(curves.empty()){
		m_dlg.m_TargetKind=2;
	}
	MGPickObjects surfaces;
	picked.select_fsurfaces(surfaces);
	if(surfaces.empty()){
		m_dlg.m_TargetKind=1;
	}
	if(!input_param()){
		// cancel
		return MGSelectState::OnCommandEnd(3);
	}

	std::vector<MGPosition> tmp;
	if(m_dlg.m_bEnd){
		MGSnapPositions ends(MGSnapPositions::endpos);
		ends.extract(picked);
		ends.append_position_data(tmp);
	}
	if(m_dlg.m_bKnot){
		MGSnapPositions knots(MGSnapPositions::knotpos);
		knots.extract(picked);
		knots.append_position_data(tmp);
	}

	if(m_dlg.m_bCenter){
		MGSnapPositions centers(MGSnapPositions::centerpos);
		centers.extract(picked);
		centers.append_position_data(tmp);
	}
	if(m_dlg.m_bVertex){
		MGSnapPositions vertices(MGSnapPositions::vertexpos);
		vertices.extract(picked);
		vertices.append_position_data(tmp);
	}

	MGGelPositions gelps;
	MGGroup* cgroup=document()->current_group();
	size_t n=tmp.size();
	for(size_t i=0; i<n; i++){
		gelps.push_back(MGGelPosition(cgroup,new MGPoint(tmp[i])));
	}

	add_object_to_document(gelps);
	return MGSelectState::OnCommandEnd(1);
}
