/*------------------------------------------------------------------------------*
 * File Name:				 													*
 * Creation: 																	*
 * Purpose: OriginC Source C file												*
 * 																				*
 * Modification Log:															*
 *Joseph 06/06/07 MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE	*
 *------------------------------------------------------------------------------*/
 
//--------------------------------------------------------------------------
// You can include just this typical header file for most Origin built-in
// functions and classes and it takes a reasonable amount of time to compile, 
// This file include most of the other header files except the NAG header, which
// takes longer to compile NAG routines.

//--------------------------------------------------------------------------
#include <origin.h>
//#include <OC_nag.h> // Optional. Contains all NAG header files.
#include "DialogEx.h"
#include <tree.h>
#include "TXdefines.h"
#include <..\originlab\xfunctionEx.h>



#define STR_DOC_DESCRIP_SECTION				"Description"
#define STR_DOC_HELP_INFO_SECTION			"Info"
#define STR_DOC_HELP_SUMMARY_SECTION		"Summary"
#define STR_DOC_HELP_EXAMPLE_SECTION		"Examples"
#define STR_DOC_HELP_REFERENCE_SECTION		"Reference"
#define STR_DOC_HELP_SEEALSO_SECTION		"See Also"
///Joseph 06/06/07 MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE
//centerlize the code
/*
#define STR_LANGUAGE_ENGLISH				"English"
#define STR_LANGUAGE_JAPANESE				"Japanese"
#define STR_LANGUAGE_GERMAN					"German"
#define STR_LANGUAGE_CHINESE				"Chinese"
*/
///End MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE

///-- OC bugs, not need this in new build.
#define IDD_TX_DISPLAY                  169
#define IDC_TX_MENU_PRINT               40037
#define IDC_TX_MENU_SAVE                40038
#define IDC_TX_MENU_INSERT_EQUATION     40039
#define IDC_TX1                         2439
///---

#define TEMPLATE_FILE_NAME "TXTemplate.rtf"    // use RTF as TX has a bug for bookmark in doc
///Joseph 06/06/07 MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE
/*
enum 
{
	LANG_ALL = 0,
	LANG_ENGLISH,
	LANG_JAPANESE,
	LANG_GERMAN,
	LANG_CHINESE
};
*/
///End MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE
static bool _save_doc(LPCSTR lpcszFile, const vector<char>& vcDoc)
{
	file ff;
	if(ff.Open(lpcszFile, file::modeWrite | file::shareExclusive | file::modeCreate))
	{
		int nSize = vcDoc.GetSize();
		void* lp = (char*)vcDoc;
		ff.Write(lp, nSize); 
		ff.Flush();
		ff.Close();
		//printf("success in writing into %s, size = %d\n", lpcszFile, nSize);
		return true;
	}
	return false;
}


static bool _get_help_text(vector<char>& vc, const TreeNode& tr, string& str)
{
	vc.SetSize(0);
	if(tr.IsEmpty())
		return false;
	if(tr.TypeID != TNVAL_TYPE_CHAR_VECTOR)
	{
		str = tr.strVal;
		if(str.GetLength() < 10000)// it seems that Word doc has a min size of about 20k, and typical text is very small
		{
			printf("failed to get vector<char> from %s node(typeid = %d), using string instead\n", tr.tagName, tr.TypeID);
			return false;
		}
	}
	try {
		vc = tr.bVals;	
	}
	catch(int nErr)
	{
		out_int("_get_help_text err = ", nErr);
		return false;
	}
	return true;	
}


/**

*/
class TXDisplayDialog: public ResizeDialog
{
public:
	TXDisplayDialog(TreeNode trXF, int nSpecifyLangIndex = LANG_ENGLISH) : ResizeDialog( IDD_TX_DISPLAY, "ODlg8" )
	{
		vector<int> vnLang = {IDRS_HELP_E, IDRS_HELP_J, IDRS_HELP_G, IDRS_HELP_C};
		vector<string> vsLang = {STR_LANGUAGE_ENGLISH, STR_LANGUAGE_JAPANESE, STR_LANGUAGE_GERMAN, STR_LANGUAGE_CHINESE};
		
		if ( nSpecifyLangIndex >= LANG_ENGLISH && LANG_ENGLISH < LANG_ALL )   // later, need move this checking out of constructor
		{
			//temp codes, don't know why GZ later use xf even after get trXF
			int nIndex = nSpecifyLangIndex - LANG_ENGLISH;
//			m_nLang = vnLang[nIndex];
//			m_sLangName = vsLang[nIndex];
		}
		m_trXF = trXF;
	}
	
	int DoModalEx(HWND hParent)
	{
		InitMsgMap();// will be called from internal later
		int nRet = DoModal(hParent);
		if(IDOK == nRet)
		{
			return 1;
		}
		return 0;
	}	
protected:
	
EVENTS_BEGIN
	ON_INIT(OnInitDialog)
	ON_READY(OnReady)
	ON_DESTROY(OnDestroy)
	ON_SIZE(OnDlgResize)
	ON_MENU_CMD(IDC_TX_MENU_PRINT, OnPrint)
	ON_MENU_CMD(IDC_TX_MENU_SAVE, OnFileSave)
	ON_MENU_CMD(IDC_TX_MENU_INSERT_EQUATION, OnInsertEquation)
EVENTS_END
	BOOL OnInitDialog()
	{		
		ResizeDialog::OnInitDialog(0, "TX Diaply dialog"); // str for reg remembering dialog pos etc info
		
		Control TXTextControl;
		TXTextControl = GetItem(IDC_TX1);
		
	
		if(TXTextControl)
			m_txText = TXTextControl.GetActiveXControl();
		if ( m_txText )
		{
			try
			{
				m_txText.Load(okutil_get_origin_path(ORIGIN_PATH_SYSTEM)+TEMPLATE_FILE_NAME, 0, TX_FILE_RTF);  // load template file
				m_txText.ViewMode = 0;
			}
			catch(int nError)
			{
				printf("failed to open %s", TEMPLATE_FILE_NAME);
			}
			return LoadXF();
			
		}
		else
			return false;
		
		return true;
		
	}	
	BOOL OnReady()
	{		
		SetInitReady();
		return true;
	}
	BOOL OnDestroy(void)
	{
		ResizeDialog::OnDestroy();
		OnFileSave();
		return true;
	}
	BOOL OnDlgResize(int nType, int cx, int cy)
	{
		if(!IsInitReady())
			return TRUE;

		PositionControl(IDC_TX1,0,0);
		SizeControl(IDC_TX1, cx, cy);
		return TRUE;
	}
	BOOL	LoadXF()
	{
		//description
		TreeNode trDescription=m_trXF.xFdescription;	//get xf description node
		string str;
		str = trDescription.strVal;
		InsertTextSring(STR_DOC_DESCRIP_SECTION, str);

		
		//Get Help node
		TreeNode trHelp = m_trXF.helpe;    // temp code, old code need use xf
		vector<uint> vnHelpNodeIDs={IDV_HELP_SUMMARY, IDV_HELP_EXAMPLE, IDV_HELP_REF};
		vector<string> vsHelpLabels={STR_DOC_HELP_INFO_SECTION, STR_DOC_HELP_SUMMARY_SECTION, STR_DOC_HELP_EXAMPLE_SECTION, STR_DOC_HELP_REFERENCE_SECTION, STR_DOC_HELP_SEEALSO_SECTION};
		vector<char> vcVals;
		TreeNode trTemp;
		
		for(int ii=1; ii<vsHelpLabels.GetSize(); ii++)  //vsHelpLabels.GetSize()
		{
			trTemp = trHelp.Children.Item(ii);
			string strValOnErr;
			if(_get_help_text(vcVals, trTemp, strValOnErr))
			{
				//_save_doc(vsHelpLabels[ii], vcVals); 
				InsertBinarySring(vsHelpLabels[ii], vcVals, TX_FILE_DOC);
			}
			else
			{
				/// ????
				InsertTextSring(vsHelpLabels[ii], strValOnErr);
				//ASSERT(false);
			}
		}
		
		return true;
	}
	
	BOOL InsertBinarySring( LPCSTR strBookMark, vector<char>& vc, int nFormatID = TX_FILE_DOC)
	{
		if ( GetBookMarkPlace( strBookMark) )
		{
			_VARIANT  var;
			var = vc.GetDataAsOneDimensionalArray();
			bool bOK =  m_txText.LoadFromMemory( var, TX_FILE_DOC, 1);
			if ( bOK )
				return true;
			else
			{
				printf("Fail to load binary to file");
				ASSERT(false);
			}
		}
		return false;
	}
	
	BOOL InsertTextSring( LPCSTR strBookMark, string& strVal)
	{
		if ( GetBookMarkPlace( strBookMark) )
		{
			m_txText.SelText  = strVal;	
			return true;
		}
		return false;
	}
	BOOL GetBookMarkPlace(LPCSTR strBookMark)
	{
		int nFieldID = 0;
		do 
		{
			nFieldID = m_txText.FieldNext(nFieldID, 0);
			if ( nFieldID > 0 )
			{
				string strtemp = m_txText.FieldData(nFieldID);
				if ( strtemp.Compare(strBookMark) == 0 )
					break;
			}
		}while ( nFieldID > 0 );
		if ( nFieldID > 0 )
		{
			m_txText.FieldCurrent = nFieldID;
	        m_txText.SelStart = m_txText.FieldStart - 1;
	        m_txText.SelLength = m_txText.FieldEnd - m_txText.FieldStart + 1
		}
		else
		{
			printf("Wrong book mark %s", strBookMark);
			return false;
		}
		return true;
	}
	
	BOOL	OnFileSave()
	{
		// temp file to check result for testing
		m_txText.Save(okutil_get_origin_path(ORIGIN_PATH_SYSTEM)+"TXresult.rtf", 0, TX_FILE_RTF);
		return true;
	}
	BOOL OnPrint()
	{
		// temp simple testing codes for print
		m_txText.PrintDoc("Test TX", 1, 2, 1);		
		return true;		
	}
	BOOL OnInsertEquation()
	{
		m_txText.ObjectInsert(TX_OLE_INSERT_OBJECT_WITH_PROGID, "Equation.3", -1, 0, 0, 0, 100, 100, 3, 100, 100, 100, 100);
		return true;
	}
	
protected:
	
	Object	m_txText;
	Tree	m_trXF;
};

bool display_xf_document(string strXFName = "smooth", int nSpecifyLangIndex = LANG_ENGLISH)
{
	string strOXF;
	if(okutil_find_file_from_map(&strOXF, SUPPORTFILE_XF, ORIGIN_PATH_UNDEF, strXFName) == ORIGIN_PATH_UNDEF)
	{
		//out_str("Can not find x-funtion: "+strXFName);
		out_str(XF_FIND_ERROR_PRE +  STR_PREFIX_NAME_SEP +strXFName);
		return false;
	}
	
	XFunction xf; 
	Tree trXF;
	if(!xf.Load(trXF, strOXF))
	{
		printf("err loading %s\n", strOXF);
		return false;    
	}
	//---- CPY 9/2/05	CHECK_EMPTY_HELP_NODES
	string strXFname = xf.GetFunctionName(false);
	printf("Processing %s, destination folder = %s\n", strXFname);
	//----
	
	TXDisplayDialog txDisplayDlg(trXF, nSpecifyLangIndex);
	return txDisplayDlg.DoModalEx(GetWindow());
	
}



