/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/* ***************************************************** */
/********************************************************************/
/**
 * @file EvalTextDumpTool.cpp
 * @brief EvalTextDumpTool.h の実装
 */
#include "stdafx.h"
//#include "fugen.h"
#include "EvalCmd/EvalTextDumpTool.h"

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

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

bool MGEvalTextDumpTool::can_break_into() const
{
	// ピックオブジェクトがない場合はインタラクティブにならざるを得ない。
	return !current_objects().empty();
}

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

bool MGEvalTextDumpTool::initiate_tool(){
	MGCommandBase::initiate_tool();
	if(!Execute()){
		return OnCommandEnd(2);
	}

	return OnCommandEnd(1);
}

void MGEvalTextDumpTool::DisplayErrorMessage(UINT nIDS)
{
	CString strMsg, str;
	strMsg.LoadString(nIDS);
	str.Format(IDS_ERROR, strMsg);
	putInOutputWindow(str);
}

bool MGEvalTextDumpTool::Execute()
{
	const DWORD dwBufLen = MAX_PATH * 4;
	TCHAR path[dwBufLen];
	std::fill_n(path, dwBufLen, 0);

	if(!::GetTempPath(dwBufLen, path)){
		DisplayErrorMessage(IDS_FAIL_GET_TEMP_PATH);
		return false;
	}

	CString strFileName = CTime::GetCurrentTime().Format("fugendump-%Y%m%d%H%M%S.txt");
	if(!::PathAppend(path, strFileName)){
		DisplayErrorMessage(IDS_FAIL_GET_TEMP_FILE_NAME);
		return false;
	}

	std::ofstream fout(path);
	if(!fout){
		DisplayErrorMessage(IDS_FAIL_OPEN_TEMP_FILE);
		return false;
	}

	if(current_objects().empty()){
		fout << *doc_root();
	}
	else{
		const MGPickObjects& curobj = current_objects();
		MGPickObjects::const_iterator first = curobj.begin(), last = curobj.end();
		for(; first != last; ++first){
			fout << *(**first).top_object() << std::endl;
		}
	}
	fout.close();

	size_t ret = reinterpret_cast<size_t>(::ShellExecute(
		AfxGetMainWnd()->GetSafeHwnd(),
		_T("open"), path, 0, 0, SW_SHOWNORMAL));
	if(ret < 32){
		DisplayErrorMessage(IDS_FAIL_SHELL_EXECUTE);
		return false;
	}

	return true;
}
