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

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

// MGSurfShrinkTool

MGSurfShrinkTool::MGSurfShrinkTool(fugenDoc* pDoc)
	 : MGSelectState(
		 pDoc,
		 ID_SURFACE_SHRINK,
		 MULTIPLE_SELECT,
		 mgAll_Face),
	   m_nIDS(1)
{
}

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

bool MGSurfShrinkTool::initiate_tool(){
	MGSelectState::initiate_tool();
	resetCurrentObjects(mgAll_Face);
	if(current_objects().empty()){
		prompt_message();
		return false;
	}

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

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

	const MGPickObjects& curobj = current_objects();
	if(curobj.empty()){
		// オブジェクトが指定されていないのでキャンセル扱い
		return false;
	}

	// iteration..
	MGGelPositions gelps;
	MGPickObjects::const_iterator first = curobj.begin(), last = curobj.end();
	for(; first != last; ++first){
		ASSERT((*first)->top_object());

		MGFace* face = dynamic_cast<MGFace*>((*first)->top_object());
		if(!face){
			continue;
		}

		std::unique_ptr<MGFace> f(mgcalc::shrink(*face));
		if(!f.get()){
			continue;
		}

		gelps.push_back(MGGelPosition((*first)->bottom_group(),f.release()));
	}

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

	replace(curobj,gelps);
	return true;
}

bool MGSurfShrinkTool::OnSelected(
	fugenView* pView,
	MGPickObjects& selobj,
	MGPickObjects& remobj
	){
	ASSERT(!selobj.empty());
	
	// 計算可能状態
	if(!calculate()){
		// 失敗...
		return OnCommandEnd(m_nIDS);
	}
	return OnCommandEnd(1);
}

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