#include <origin.h>
#include <GetNBox.h>
#include <xfutils.h>
//put additional include files here
#include <XFbase.h>
#include <GetNBox.h>
#include <..\originlab\theme_utils.h> ///---Sim 10-27-2008 QA80-12422 SUPPORT_SAVE_SHEET_THEME_FOR_ALL_SHEET_IMPORT_FILE
//#include <..\originlab\file_utils.h>
//#include <..\originlab\Import_Utils.h>
#include <..\originlab\fu_utils.h>
/// Hong 02/16/07 FIX_FAIL_COMPLIE
#ifdef _FOR_SMART_LOADING_ONLY
	#include <..\originlab\file_utils.h>
#endif // _FOR_SMART_LOADING_ONLY
/// end FIX_FAIL_COMPLIE
#include <..\originlab\FamosFile.h>
//put your own support static functions here
///////////////////////////////////////////////////////////////////////
//////// modification log
/// Hong 03/28/07 v8.0591 CENTRALIZE_CHECK_CALID_RANGE
/// Hong 04/10/07 v8.0597b IGNORE_FNAME$_WHEN_FROM_MENU
/// Sim 04-30-2007 TEMP_FIX_IMPORT_MODE_FOR_SINGLE_FILE
/// Sim 05-08-2007 ADD_OPTIONS_FOR_IMPORT_MODE_OF_1ST_FILE
/// Sim 05-18-2007 REMOVE_UID_VARIABLE
/// Sim 06-25-2007 UPDATE_ORGANIZER
/// Sim 08-06-2007 SUPPORT_SMART_SPARKLINE
/// Hong 09/26/07 8.0709 CLEAN_OPEN_SAVE_DIALOG_TITLE_TO_DEFAULT
/// Sim 10-27-2008 QA80-12422 SUPPORT_SAVE_SHEET_THEME_FOR_ALL_SHEET_IMPORT_FILE
/// Hong 03/09/10 QA80-14858-P5 AUTO_RENAME_WKS_COVER_IMPORTANT_CHANNEL_NAME_FROM_FILE
///////////////////////////////////////////////////////////////////////


#define FAMOS_1ST_FILE_IMPORT_MODE_LIST 	LIST_IMPORT_MODE_REPLACE_BOOK_SHEET_COLUMN ///---Sim 05-08-2007 ADD_OPTIONS_FOR_IMPORT_MODE_OF_1ST_FILE
#define FAMOS_IMPORT_MODE_LIST	(FAMOS_1ST_FILE_IMPORT_MODE_LIST & (~IW_FLAG_IMPMODE_REPLACE)) ///---Sim 05-08-2007 REMOVE_REPLACE_OUT_OF_MULTI_FILE_IMPORT_MODE

static bool s_bFileValid = true;
static bool s_bRangeValid = true;
#define OK_SURE(_OK_ENABLE) _OK_ENABLE = (s_bFileValid && s_bRangeValid);

static BOOL _construct_tree_setting(StringArray& vsFileNames, TreeNode& trInfo)
{
	int nCount = vsFileNames.GetSize();
	string strFileName, strTag, strInfo;
	if ( trInfo )
		trInfo.RemoveChildrenWithPrefix();
	
	GETN_USE(trInfo)
	for ( int nIndex = 0; nIndex < nCount; nIndex++ )
	{
		strFileName = vsFileNames[nIndex];
		if ( !strFileName.IsFile() )
			return false;

		strTag.Format("file%d", nIndex+1);
		strInfo.Format("File Size: %s ", GetFileSize(strFileName));
		GETN_STR(strTag, GetFileName(strFileName, false), strInfo )
		GETN_READ_ONLY
	}
	return true;
}

static bool _file_name_event(TreeNode& trGetN, string& strErrMsg)
{
	string strFileName = trGetN.fname.strVal;
	TreeNode trNode = trGetN.trfiles;
	
	trNode.RemoveChildrenWithPrefix();
	
	if (!check_imported_file_name(strFileName, strErrMsg))
		return false;
	
	StringArray vsFileNames;
	separate_multiline_files(strFileName, vsFileNames);
	if ( !_construct_tree_setting(vsFileNames, trNode) )
	{
		// clean the info on GUI
		trNode.RemoveChildrenWithPrefix();
		strErrMsg = CER_INVALID_IMPORT_DATA_FILE;
		return false;
	}
	
	return true;
}


void impFamos(const string& fname, const TreeNode& trfiles, const TreeNode& options, Range& orng, TreeNode& trheader)
{
	
	//vector vImportedRangeUID; ///---Sim 05-18-2007 REMOVE_UID_VARIABLE remove
	
	int c1,c2; 
	Datasheet ds;
	/// Hong 03/28/07 v8.0591 CENTRALIZE_CHECK_CALID_RANGE
	//orng.GetRange(ds, c1, c2);
	Page pgTarget;
	if ( !GetRangeInfo(orng, ds, pgTarget, c1, c2) )
		XF_THROW(XFERR_INVALID_RANGE);
	/// end CENTRALIZE_CHECK_CALID_RANGE
	Worksheet ws = ds;
	if ( !ws )
		XF_THROW(CER_INVALID_WKS);
	/// Hong 03/28/07 v8.0591 CENTRALIZE_CHECK_CALID_RANGE
	//Page pgTarget;
	//ws.GetParent(pgTarget);
	/// end CENTRALIZE_CHECK_CALID_RANGE
	
	///---Sim 03-09-2007 TEMP_FIX_HIGHLINE_REPLACE_DATA	
	/// Hong 09/08/07 v8.0698b FIX_FAIL_DUMP_OUTPUT_RANGE_ORNG
	/*
	if ( orng )
	{
		orng.Reset();
		orng.Add(ds, 0);
	}
	*/
	reset_range_to_first_obj(orng, ds);
	/// end FIX_FAIL_DUMP_OUTPUT_RANGE_ORNG
	///---END TEMP_FIX_HIGHLINE_REPLACE_DATA
	
	
	Tree trBaseInfo; 
	/// Hong 01/10/06 FINFO_IS_ONLY_OUTPUT
	//if ( finfo )
		//trBaseInfo = finfo;
	/// end FINFO_IS_ONLY_OUTPUT
	TreeNode tnUsingFilter; // filter is none
	double dDefault = 0.;
	if ( fuGetDouble(options, IDE_DISP_IMP_ORIGINVER, dDefault) )
		tnUsingFilter = options;
	
	int nFileImportMode = fuGetImportMode(tnUsingFilter);
	
	///---Sim 08-06-2007 SUPPORT_SMART_SPARKLINE
	//bool bSparkLines = fuGetSparkLine(tnUsingFilter);
	int nSparklines = fuGetSparkLine(tnUsingFilter);
	///---END SUPPORT_SMART_SPARKLINE
	
	StringArray vsFileNames;
	separate_multiline_files(fname, vsFileNames);
	int nFileCount = vsFileNames.GetSize();
	if ( nFileCount <= 0 )
		XF_THROW(CER_INVALID_IMPORT_DATA_FILE);
	
	vector<int> vnEmptyLayers;
	
	int nC1;
	int nIndexLayer = ws.GetIndex();
	for (int nFileIndex = 0; nFileIndex < nFileCount; nFileIndex++ )
	{
		///---Sim 04-30-2007 TEMP_FIX_IMPORT_MODE_FOR_SINGLE_FILE
		//if ( 0 == nFileIndex )
		//{
			//int nImportMode = get_first_file_import_mode(FILE_TYPE_FAMOS);
			//TreeNode trInValid;
			//
			//ws = GetTargetLayer(pgTarget, nIndexLayer, nFileIndex, trInValid, true, orng, nImportMode, nC1);
		//}
		//else
		//{
		ws = GetTargetLayer(pgTarget, nIndexLayer, nFileIndex, tnUsingFilter, true, orng, nFileImportMode, nC1);
		//}
		///---END TEMP_FIX_IMPORT_MODE_FOR_SINGLE_FILE
		
		/// Hong 01/10/06 FINFO_IS_ONLY_OUTPUT
		//Tree trInfo;
		//trInfo.Replace(trBaseInfo);
		string strFile;
		strFile.Format("File%d", nFileIndex + 1); // file index to be 1
		TreeNode trInfo = trBaseInfo.AddNode(strFile);
		/// end FINFO_IS_ONLY_OUTPUT
		
		bool bSampleInterval = false;
		Layer ly = ws;
		FamosFile famosFile(vsFileNames[nFileIndex]);
		int nRet = famosFile.Import(ly, trInfo, bSampleInterval, nC1);
		//ly.SetName(GetFileName(vsFileNames[nFileIndex], true));
		if ( nRet )
		{
			XF_THROW_EX(nRet, vsFileNames[nFileIndex]);
		}
		/// Sophy 5/04/2008 SHOW_WARNING_MESSAGE_WHEN_IMPORT_INVALID_DATA_FILE
		if( !famosFile.HasImportedData() )
		{
			warning_msg_box(CER_NO_DATA_IMPORT_FROM_FILE, vsFileNames[nFileIndex], false);
		}
		/// End SHOW_WARNING_MESSAGE_WHEN_IMPORT_INVALID_DATA_FILE
		// rename 
		setPageAndLayerName(famosFile.GetDataRange(), vsFileNames[nFileIndex], tnUsingFilter);
		
		if ( is_sheet_empty(ws) )	// data import to matrix
		{
			vnEmptyLayers.Add(ws.GetIndex());
		}
		else
		{
			///---Sim 08-06-2007 SUPPORT_SMART_SPARKLINE
			/*
			if ( bSparkLines )
			{
				XFBase xfSparkLine("sparklines");
				if( !xfSparkLine )
				{
					//XF_THROW(CER_FAILED_LOAD_SPK_LINE_XF);///---Sim 11-09-2006 HANDLE_ERROR_MESSAGE
					XF_WARN(CER_FAILED_LOAD_SPK_LINE_XF);
				}
				else
				{
					famosFile.GetDataRange().GetRange(ws, c1, c2);
					xfSparkLine.SetArg("sel", 0);
					xfSparkLine.SetArg("c1", c1+1);
					xfSparkLine.SetArg("c2", c2+1);
					xfSparkLine.SetArg("wks", ws);
					
					if ( !xfSparkLine.Evaluate() )
						//XF_THROW(CER_SPK_LINE_RUN_ERROR); ///---Sim 11-09-2006 HANDLE_ERROR_MESSAGE
						XF_WARN(CER_SPK_LINE_RUN_ERROR);
				}
			}
			*/
			bool bSparklines = update_sparkline(nSparklines, ws, c1, c2);
			///---END SUPPORT_SMART_SPARKLINE
			
			//vector<int> vn = {RCLT_LONG_NAME, RCLT_UNIT, RCLT_COMMENT};
			vector<int> vnIDs;
			vector<uint> vIndex;
			wks_get_show_labels(ws, vnIDs);
			if ( bSampleInterval && vnIDs.Find(vIndex, RCLT_SAMPLE_RATE) <= 0 )
				vnIDs.Add(RCLT_SAMPLE_RATE);
			///---Sim 08-06-2007 SUPPORT_SMART_SPARKLINE
			//if ( bSparkLines && vnIDs.Find(vIndex, RCLT_SPARKLINE) <= 0)
			if ( bSparklines && vnIDs.Find(vIndex, RCLT_SPARKLINE) <= 0)
			///---END SUPPORT_SMART_SPARKLINE
				vnIDs.Add(RCLT_SPARKLINE);	
				
			wks_add_show_labels(ws, vnIDs, false);
		}
		
		// add data range info
		Tree trDataRange;
		///---Sim 05-18-2007 REMOVE_UID_VARIABLE
		//int UID = getRangeInfo(trDataRange, famosFile.GetDataRange());
		getRangeInfo(trDataRange, famosFile.GetDataRange());
		//vImportedRangeUID.Add(UID);
		///---END REMOVE_UID_VARIABLE
		
		// if current file cover existing file data, need update info of that files
		impinfo_UpdateExistingData(pgTarget, famosFile.GetDataRange());
	
		impinfo_AddFile(ly, vsFileNames[nFileIndex], trInfo, ASCIMP_MODE_NEW_SHEETS, FILTER_TYPE_XFUNC, tnUsingFilter, nFileIndex + 1, trDataRange);
	}
	
	// clean empty sheets
	Layer ly = Project.ActiveLayer();
	for ( int ii = vnEmptyLayers.GetSize() - 1; ii >= 0; ii-- )
	{
		if(vnEmptyLayers[ii])
			pgTarget.Layers(vnEmptyLayers[ii]).Destroy();
	}
	set_active_layer(ly);
	
	//refresh_organizer_gui(pgTarget); ///---Sim 06-25-2007 UPDATE_ORGANIZER
	///---Sim 05-18-2007 REMOVE_UID_VARIABLE
	//if ( uid )
		//uid = vImportedRangeUID;
	///---END REMOVE_UID_VARIABLE
	if ( trheader )
		trheader.Replace(trBaseInfo.Clone(), true, true);/// Hong 01/10/06 FINFO_IS_ONLY_OUTPUT
}

//nEventID < 0 on event, like GETNE_ON_INIT, GETNE_ON_OK etc, >0 on change from control
//return 0 to do nothing, return PEVENT_GETN_RET_TO_CLOSE to close dialog
//dwEnables = bOKEnable, bBTN1Enable, bBTN2Enable, bBTN3Enable, , can set to false to disable OK/Apply buttons
//lpcszNodeName = the trGetN TreeNode tag name that generates the event, or is  if GETNE_ON_OK etc
//strAux = optional string for XF Wizard Bar, like DLG_NEED_CHANGE_GRID etc, it will be invalid if from internal node value change event
//strErrMsg = allowing messages to be shown
int impFamos_event1(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	if( xf_is_extended_event(nEventID) )
		return impFamos_event1_ex(trGetN, nRow, nEventID, dwEnables, lpcszNodeName, DynaCntrlContainer, strAux, strErrMsg);
	DECLARE_BUTTON_ENABLES
	OK_SURE(bOKEnable);
	
		///support D&D show Dlg, if trFiles no child, should construct it
	if ( (GETNE_ON_INIT == nEventID && trGetN.trfiles.Children.Count() == 0) || GETNE_ON_THEME == nEventID )
	{
		s_bFileValid = _file_name_event(trGetN, strErrMsg);
		s_bRangeValid = !trGetN.orng.strVal.IsEmpty();
		if(!s_bRangeValid)
			strErrMsg = CER_INVALID_PAGE;
		
		OK_SURE(bOKEnable);	
		return true;
	}
	
	//check file name if is invalid
	if ( 0 == lstrcmp(lpcszNodeName, "fname") )
	{
		s_bFileValid = _file_name_event(trGetN, strErrMsg);
		OK_SURE(bOKEnable);
		return true;
	}
	
	//check range if is invalid
	if( 0 == lstrcmp(lpcszNodeName, "orng") )
	{
		s_bRangeValid = !trGetN.orng.strVal.IsEmpty();
		if(!s_bRangeValid)
			strErrMsg = CER_INVALID_PAGE;
		
		OK_SURE(bOKEnable);
		return true;
	}
	return false;

}

int impFamos_make_tree(TreeNode& tr, LPCSTR lpcszVarName)
{
	
	if ( 0 == strcmp(lpcszVarName, "options") )
	{
		constructOptionsForXF(tr, true, true, true);
		
		// custom import mode list
		///---Sim 05-08-2007 ADD_OPTIONS_FOR_IMPORT_MODE_OF_1ST_FILE
		TreeNode tr1stImportMode = tree_get_node_by_id(tr, IDE_DISPIMP_1STMODE, true);
		if ( tr1stImportMode )
		{
			string strCombo, strMapping;
			strCombo = getImportModeListString(strMapping, FAMOS_1ST_FILE_IMPORT_MODE_LIST);
			tr1stImportMode.SetAttribute(STR_COMBO_ATTRIB, strCombo);
			tr1stImportMode.SetAttribute(STR_INTMAP_ATTRIB, strMapping);
			tr1stImportMode.nVal = ASCIMP_MODE_REPLACE_DATA;
		}
		///---END ADD_OPTIONS_FOR_IMPORT_MODE_OF_1ST_FILE
		TreeNode trImportMode = tree_get_node_by_id(tr, IDE_IMP_IMPORTMODE, true);
		if ( trImportMode )
		{
			string strCombo, strMapping;
			strCombo = getImportModeListString(strMapping, FAMOS_IMPORT_MODE_LIST);
			trImportMode.SetAttribute(STR_COMBO_ATTRIB, strCombo);
			trImportMode.SetAttribute(STR_INTMAP_ATTRIB, strMapping);
			trImportMode.nVal = ASCIMP_MODE_NEW_SHEETS;
		}
		/// Hong 03/09/10 QA80-14858-P5 AUTO_RENAME_WKS_COVER_IMPORTANT_CHANNEL_NAME_FROM_FILE
		fuSetRenameWks(tr, 0);
		/// end AUTO_RENAME_WKS_COVER_IMPORTANT_CHANNEL_NAME_FROM_FILE
		fuSetXFunctionName(tr, "impFamos");
	
		return 0;
	}
	
	return -1;
}
//nGetNDialog = 0,1,2, corresponding to the XF GetN dropdown, 0 = dialog is not used
//you can change nRet to be one of XFEVT_PROCEED (defualt), XFEVT_ABORT, XFEVT_PROCEED_NO_DLG or XFEVT_PROCEED_WITH_DLG(when nGetNDialog = 0)
//nGetNDialog = -1 when Ok on GetN dialog to allow handler to preocess <auto> etc variables
//dwCntrl is combination of bits
//LTXF_FROM_GUI_MENU, LTXF_FROM_GUI_PROMPT, LTXF_FROM_AUTO_UPDATE, LTXF_FROM_FUNCTION, LTXF_THEME_USED, LTXF_CHANGE_PARAM
void impFamos_before_execute(TreeNode& trGetN, int nGetNDialog, int& nRet, int dwCntrl)
{
	if ( nGetNDialog > 0 )
	{
	//		trGetN.orng.Show = 0;
		//trGetN.uid.Show = 0; ///---Sim 05-18-2007 REMOVE_UID_VARIABLE
		trGetN.trheader.Show = 0;
		//trGetN.trFilter.Show = 0;
	}
	if(nGetNDialog >= 0)
	{
		if ( LTXF_FROM_GUI_MENU == dwCntrl )
			trGetN.fname.strVal = "";
		//TreeNode trFilter = trGetN.trFilter;
		//if ( trFilter.IsValid() && trFilter.GetNodeCount()>0 )
			//trGetN.sparklines.nVal = fuGetSparkLine(trFilter);
	}
	if(nGetNDialog > -1)
	{
		string strFileName = trGetN.fname.strVal;
		
		/// Hong 04/10/07 v8.0597b IGNORE_FNAME$_WHEN_FROM_MENU
		if ( LTXF_FROM_GUI_MENU & dwCntrl ) // if from menu, ignore default value fname$
			strFileName = "";
		/// end IGNORE_FNAME$_WHEN_FROM_MENU
		
		if(is_empty_or_unassigned(strFileName))
		{			
			/// Hong 05/31/07 v8.0630 MORE_ON_ACCESS_TO_FDLOG
			//int nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", "Famos File", true);
			int nFilesRet;
			if ( 0 != nGetNDialog )
			{
				int nShowOptionsDlg = 1;
				/// Hong 09/26/07 8.0709 CLEAN_OPEN_SAVE_DIALOG_TITLE_TO_DEFAULT
				//nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", _L("Famos File"),
				//	OPENBOX_FLAG_MULTIFILES, NULL, NULL, _L("Show Options Dialog"), &nShowOptionsDlg);
				///---Sim 10-27-2008 QA80-12422 SUPPORT_SAVE_SHEET_THEME_FOR_ALL_SHEET_IMPORT_FILE
				//nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", NULL,
					//OPENBOX_FLAG_MULTIFILES, NULL, NULL, STR_SHOW_OPT_DLG, &nShowOptionsDlg);
				nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", NULL,
					OPENBOX_FLAG_MULTIFILES, NULL, NULL, get_show_options_label(trGetN), &nShowOptionsDlg);
				///---END QA80-12422 SUPPORT_SAVE_SHEET_THEME_FOR_ALL_SHEET_IMPORT_FILE
				/// end CLEAN_OPEN_SAVE_DIALOG_TITLE_TO_DEFAULT
				nRet = (nShowOptionsDlg ? XFEVT_PROCEED : XFEVT_PROCEED_NO_DLG);
			}
			else
			{
				//nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", _L("Famos File"), true);
				nFilesRet = get_open_box_by_file_group(strFileName, "FAMOS", NULL, true); /// Hong 09/26/07 8.0709 CLEAN_OPEN_SAVE_DIALOG_TITLE_TO_DEFAULT
			}
			/// end MORE_ON_ACCESS_TO_FDLOG
			if ( 0 == nFilesRet )
			{
				nRet = XFEVT_ABORT;
				//warning_msg_box(XFERR_UI_USER_CANCEL, false);
				return;
			}
			trGetN.fname.strVal = strFileName;
			string strErrMsg;
			if( !_file_name_event(trGetN, strErrMsg) )
			{
				/// Hong 03/21/07 v8.0586 FIX_FAIL_DUMP_CORRECT_ERROR_STRING
				//nRet = XFEVT_ABORT;
				//warning_msg_box(strErrMsg, false);
				int nErrMsg = atoi(strErrMsg);
				nRet = XFEVT_ABORT;
				warning_msg_box(nErrMsg, false, 'E'); // should pass an int ///---Sim 06-19-2007 IMPROVE_WARNING_MESSAGE_POST_FUNCTION
				/// end FIX_FAIL_DUMP_CORRECT_ERROR_STRING
				return;
			}
		}
	}	
}
//nEventID < 0 on event, like GETNE_ON_INIT, GETNE_ON_OK etc, >0 on change from control
//return 0 to do nothing, return PEVENT_GETN_RET_TO_CLOSE to close dialog
//dwEnables = bOKEnable, bBTN1Enable, bBTN2Enable, bBTN3Enable, , can set to false to disable OK/Apply buttons
//lpcszNodeName = the trGetN TreeNode tag name that generates the event, or is  if GETNE_ON_OK etc
//strAux = optional string for XF Wizard Bar, like DLG_NEED_CHANGE_GRID etc, it will be invalid if from internal node value change event
//strErrMsg = allowing messages to be shown
int impFamos_event1_ex(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	return false;
}
