/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/
/********************************************************************/
/**
 * @file MergeTool.cpp
 * @brief MergeTool.h の実装
 */
#include "stdafx.h"
#include "fugen.h"
#include "fugenDoc.h"
#include "Undo/GelAddAction.h"
#include "Undo/MultiActions.h"
#include "IO/GLFileManager.h"
#include "FileCmd/MergeTool.h"
#include "IO/GLFileImporter.h"

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

/// コンストラクター
/// @param[in] pDoc コマンド対象ドキュメント
MGMergeTool::MGMergeTool(fugenDoc* pDoc)
:MGCommandBase(pDoc, ID_FILE_MERGE){
}

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

bool MGMergeTool::initiate_tool(){
	MGCommandBase::initiate_tool();
	SetStatusMessage(IDS_PROMPT_NOW_MERGING);
	std::vector<CString> newFile;
	if(!theApp.PromptFileNameMulti(newFile)){
		// キャンセル終了。
		return OnCommandEnd(3);
	}

	CWaitCursor sandglass;
	CMultiActions* actions=new CMultiActions;
	MGGroup* parent = current_group();
	CGLFileManager& factory = CGLFileManager::GetInstance();
	int nFiles=0;
	std::vector<CString>::iterator cur = newFile.begin(), last = newFile.end();
	for(; cur != last; ++cur){
		CString& fnamei=*cur;
		if(!*::PathFindExtension(fnamei))// 拡張子があるかをチェックする
			continue;

		CGLFileImporter* handler = factory.GetImporter(fnamei);
		if(!handler)
			continue;

		nFiles++;
		MGGroup group;
		handler->Load(group);

		MGGelPositions newgelps;
		MGGroup::iterator i=group.begin(), iend=group.end();
		while(i!=iend){
			auto obj = dynamic_cast<MGObject*>(i->get());
			if(obj){
				MGGelPosition gelp(parent, obj);
				newgelps.push_back(gelp);
				i->release();
				i=group.erase(i);
			}else
				i++;
		}
		actions->push_back(new CGelAddAction(document(),newgelps));
	}
	actions->Do();

	// メッセージを更新して終了
	CString str;
	str.Format(IDS_PROMPT_MERGE_N, nFiles);
	COUT << (TCAST)str << std::endl;
	return OnCommandEnd(1);
}
