/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/
/********************************************************************/
// EditExplodeTool.cpp: MGExplodeTool クラスのインプリメンテーション

#include "stdafx.h"
#include "fugenDoc.h"
#include "fugenView.h"
#include "EditCmd/EditExplodeTool.h"
#include "Calc/decomposite.h"

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

// MGExplodeTool

MGExplodeTool::MGExplodeTool(fugenDoc* pDoc)
	 : MGSelectState(
		 pDoc,
		 ID_EDIT_EXPLODE,
		 MGSelectState::SINGLE_SELECT // single pick...
		 ),
	   m_nIDS(1)
{
}

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

bool MGExplodeTool::initiate_tool(){
	MGSelectState::initiate_tool();
	const MGPickObjects& objs = current_objects();
	if(objs.size() == 1){
		MGPickObject pobj(objs.front());
		if(!calculate(pobj)){
			// failed
			clear_pick_object();
			return OnCommandEnd(m_nIDS);
		}
		// コマンド終了
		return OnCommandEnd(1);
	}
	else{
		// 強制的にクリア
		clear_pick_object();
		// 最初のメッセージ
		SetStatusMessage(IDS_PROMPT_EXPLODE_OBJECT);
	}
	return false;
}

bool MGExplodeTool::calculate(MGPickObject& obj){
	// 計算開始
	SetStatusMessage(IDS_PROMPT_COMPUTE);
	CWaitCursor sandglass;

	MGGroup gp;
	if(!mgcalc::decomposite(*obj.top_object(), gp)){
		// failed
		m_nIDS = IDS_FAIL_EXPLODE;
		return false;
	}

	std::vector<MGObject*> tmp(gp.size());
	auto i=gp.begin(), iend=gp.end();
	for(size_t j=0; i!=iend; i++, j++){
		tmp[j]=dynamic_cast<MGObject*>(i->get());
	}

	if(obj.top_object()){
		MGGelPositions gelps = make_gelpos(tmp.begin(), tmp.end(), obj.bottom_group());
		replace(obj,gelps);
		MGGroup::iterator i=gp.begin(), iend=gp.end();
		for(; i!=iend; i++) i->release();
		return true;
	}else{
		// failed
		m_nIDS = IDS_FAIL_GEL_REPLACE;
		return false;
	}
}

bool MGExplodeTool::OnSelected(
	fugenView* window,//The fugenView pointer where point input event took place.
	MGPickObjects&	objs,	//selected objects at this selection operation.
	MGPickObjects&	unselected_objects	//unselected objects at this selection operation.
		//unselected_objects.size()>=1 only when the already selected objects are selected
		//when add mode is set(or when operation is done with a crtl key pressed).
){
	ASSERT(objs.size() == 1);
	MGPickObject pobj(objs.front());
	if(!calculate(pobj)){
		return OnCommandEnd(m_nIDS);
	}
	return OnCommandEnd(1);
}
