/*
 * Sample Program for TextPorter
 *
 * Copyright (C) 2009, AntennaHouse Inc.  All Rights Reserved
 *
 * 2009.10.28 Takeshi Yoneki
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stream_oem.h"
#include "thr_func.h"

int CThreadCall::ToStreamDmc(CCmdFilePath& appfile, CCmdFilePath& txtfile) {
	int iRet = 0;
	long len = 0;
	fstream ofile;
	BOOL done = DMC_FALSE;
#ifdef DMC_WIN
	if (m_paramEncode == PE_UTF8 || m_paramEncode == PE_ASIS) {
		std::wstring tf;
		if (m_paramEncode == PE_ASIS) {
			// VS2008(VS2005以降？)でストリーム指定時に日本語の出力ファイル名が化ける問題対処。
			// 2012.02.06 Takeshi Yoneki
			tf = AnsiToUTF16((const char *)txtfile);
			appfile.m_wvalue = AnsiToUTF16(appfile.m_value);
		}
		else {
			tf = (const wchar_t *)txtfile;
		}
		ofile.open(tf.c_str(), ios::in|ios::out|ios::binary|ios::trunc);
		switch (m_funcType) {
		case FT_GET_TEXT_STREAM_V5:
			iRet= DMC_GetTextStream_V5W(appfile, &ofile, &m_textInfo_V5, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		case FT_GET_PAGE_TEXT_STREAM_V5:
			iRet= DMC_GetPageTextStream_V5W(appfile, &ofile, &m_textInfo_V5, &m_pages, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		// 2012/03/08 堀　V4の互換のStreamを追加
		case FT_GET_TEXT_STREAM_V4:
			iRet= DMC_GetTextStream_V4(appfile, &ofile, &m_textInfo_V4, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		case FT_GET_PAGE_TEXT_STREAM_V4:
			iRet= DMC_GetPageTextStream_V4(appfile, &ofile, &m_textInfo_V4, &m_pages, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		}
		done = DMC_TRUE;
	}
#endif
	if (!done) {
		ofile.open((const char *)txtfile, ios::in|ios::out|ios::binary|ios::trunc);
		switch (m_funcType) {
		case FT_GET_TEXT_STREAM_V5:
			iRet= DMC_GetTextStream_V5(appfile, &ofile, &m_textInfo_V5, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		case FT_GET_PAGE_TEXT_STREAM_V5:
			iRet= DMC_GetPageTextStream_V5(appfile, &ofile, &m_textInfo_V5, &m_pages, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		case FT_GET_TEXT_STREAM_V4:
			iRet= DMC_GetTextStream_V4(appfile, &ofile, &m_textInfo_V4, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		case FT_GET_PAGE_TEXT_STREAM_V4:
			iRet= DMC_GetPageTextStream_V4(appfile, &ofile, &m_textInfo_V4, &m_pages, (DMC_OLEERR_CALLBACK)ThreadCallBack);
			break;
		}
	}

	len = ofile.tellp();
	ofile.close();
	if(len==0){
		txtfile.Remove();
	}
	if (iRet != 0) {
		if ((m_option & DMC_GETTEXT_OPT_OLE) == 0 &&
			(m_option1 & DMC_GETTEXT_OPT1_INSERTF) == 0) { //quman add 
			// 出力サイズオーバーならファイルを消さないように修正。
			// 2008/04/18 by show
			if (iRet != FileLengthOver) {
				txtfile.Remove();
			}
		}
	}
	return iRet;
}
