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

/**
 * @file SurfPlanarTool.cpp
 * @brief MGSurfPlanarTool クラスのインプリメンテーション
 */
#include "stdafx.h"
#include "fugenDoc.h"
#include "fugenView.h"
#include "SurfCmd/SurfPlanarTool.h"
#include "mg/Point.h"
#include "Calc/planar2.h"

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

// MGSurfPlanarTool

MGSurfPlanarTool::MGSurfPlanarTool(fugenDoc* pDoc)
	 : MGSelectState(
		 pDoc,
		 ID_SURFACE_FROM_PLANAR_CURVE,
		 MGSelectState::MULTIPLE_SELECT, // multiple
		 mgAll_Curve),
	   m_nIDS(1)
{
}

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

bool MGSurfPlanarTool::initiate_tool(){
	MGSelectState::initiate_tool();
	if(!resetCurrentObjects(mgAll_Curve)){
		set_add_mode();
		// 最初のメッセージ
		SetStatusMessage(IDS_PROMPT_CURVE_PLANAR);
		return false;
	}

	// 計算可能状態
	if(!calculate()){
		// 失敗...
		return OnCommandEnd(m_nIDS);
	}
	return OnCommandEnd(1);
}

bool MGSurfPlanarTool::OnKeyDown(fugenView* pView, UINT nChar, UINT nRepCnt, UINT nFlags){
	switch(nChar){
	case VK_RETURN:
		if(resetCurrentObjects(mgAll_Curve)){
			// 計算可能状態
			if(!calculate()){
				// 失敗...
				return OnCommandEnd(m_nIDS);
			}
		}
		return OnCommandEnd(1);
	default:
		return MGSelectState::OnKeyDown(pView, nChar, nRepCnt, nFlags);
	}
}

bool MGSurfPlanarTool::calculate(){
	SetStatusMessage(IDS_PROMPT_COMPUTE);
	CWaitCursor sandglass;

	resetCurrentObjects(mgAll_Curve);
	MGPickObjects curve = current_objects();
	if(curve.empty()){
		// cancel
		return false;
	}

	mgcalc::MGPlanarSurfManager mgr;
	MGPickObjects::iterator first = curve.begin(), last = curve.end();

	for(; first != last; ++first){
		mgr.add(dynamic_cast<const MGCurve*>((**first).top_object()));
	}
	std::unique_ptr<MGGroup> group(mgr.create_face());
	if(!group.get() || group->empty()){
		// failed
		m_nIDS = IDS_FAIL_GENERATE_SURF;
		return false;
	}

	addUniqueGelsToCurrentGroup(group->begin(), group->end());
	MGGroup::iterator i=group->begin(), iend=group->end();
	for(; i!=iend; i++) i->release();
	return true;
}
