#include <origin.h>
#include <GetNBox.h>
#include <xfutils.h>
//put additional include files here
#include <sys_utils.h>

#ifdef _FOR_SMART_LOADING_ONLY
	#include <..\Originlab\file_utils.h>
#endif
#include <..\Originlab\SomatSIE.h>
#include <..\originlab\fu_utils.h>
#include <..\originlab\XFunctionEx.h>
#include <GetNBox.h>
//put your own support static functions here


#define SIE_1ST_FILE_IMPORT_MODE_LIST 	IW_FLAG_IMPMODE_REPLACE | IW_FLAG_IMPMODE_NEW_BOOKS
#define SIE_IMPORT_MODE_LIST			IW_FLAG_IMPMODE_NEW_BOOKS


static bool s_bFileValid = true;
#define OK_SURE(_OK_ENABLE) _OK_ENABLE = s_bFileValid; //also can be _OK_ENABLE = s_bFileValid && s_bSetting


int get_open_box_by_file_group(string& strFile, LPCSTR lpcszGroup, LPCSTR lpcszTitle, BOOL bMultiFiles);

static BOOL construct_tree_FileInfo(string strFileName, TreeNode& trInfo)
{
	if ( !strFileName.IsFile() )
		return false;
	string strInfo;
	strInfo.Format("File Size: %s ", GetFileSize(strFileName));
	trInfo.strVal = strInfo;
	trInfo.Enable = 0;
	return true;
}

static bool _construct_branch(TreeNode& trFile, string strFileName)
{		
	// Load file header struct to tree
	Tree trStruct;
	SIEFile fileSIE(strFileName);
	fileSIE.ReadHeader(trStruct);
	
	TreeNode trSelection, trDataGroup;
	string str, strDataGroupName;
			
	// Go to Test Group
	int nDataGroupIndex = 1;
	TreeNode trDG0 = trStruct.GetNode("TS");
	if ( !(trDG0 && trDG0.IsValid()) )
		return false;
	
	int nTestIndex = 0;
	foreach ( TreeNode trDG in trDG0.Children )
	{	
		// Add Test Tree
		str.Format("TS%d", nTestIndex);
		trSelection = trFile.AddNode(str, TRGP_BRANCH);
		str.Format("Test id %d", nTestIndex++);
		trSelection.SetAttribute(STR_LABEL_ATTRIB, str);
		trSelection.SetAttribute(STR_ATTRIB_BRANCH, GETNBRANCH_CHECK_CONTROL | GETNBRANCH_OPEN|GETNBRANCH_CHECK_CONTROL_ONE_EVENT);
		
		// Add Channel TreeNode
		TreeNode trChannelGroup;
		int nChannelGroupIndex = 1;
		TreeNode trCG = trDG.GetNode("CH");
		if ( !(trCG && trCG.IsValid()) )
			continue ;
		else
		{
			TreeNode trChannel;
			int nChannelIndex = 0;
			foreach ( TreeNode trCN in trCG.Children )
			{
				// Set default attribute
				str.Format("CH%d", nChannelIndex++);
				trChannel = trSelection.AddNumericNode(1, str, TRGP_CHECK);
				trChannel.SetAttribute(STR_LABEL_ATTRIB, trCN.Text);
			}
		}
	}
	return true;
}


static bool _construct_GUI_tree(TreeNode& trGUI, vector<string>& vsFileNames)
{
	int nCount = vsFileNames.GetSize();
	TreeNode trFile;

	trGUI.RemoveChildrenWithPrefix();

	string strTagName;
	for ( int nIndex = 0; nIndex < nCount; nIndex++ )
	{
		strTagName.Format("file%d", nIndex+1);
		trFile = trGUI.AddNode(strTagName);
		trFile.SetAttribute(STR_LABEL_ATTRIB, GetFileName(vsFileNames[nIndex], false));

		// Load File Info
		TreeNode trFileInfo;
		trFileInfo = trFile.AddNode("FileInfo");
		trFileInfo.SetAttribute(STR_LABEL_ATTRIB, STR_FILE_INFO);	///Sophy 9/21/2009 SET_LABEL_ON_GUI_FOR_TRANSLATION

		// Get file info
		if ( !construct_tree_FileInfo(vsFileNames[nIndex], trFileInfo) )
			return false;

		// Constract selection tree
		if ( !_construct_branch(trFile, vsFileNames[nIndex]) )
			return false;

	}
	trGUI.SetAttribute(STR_ATTRIB_BRANCH, GETNBRANCH_OPEN);
	
	return true;
}


static bool construct_tree_setting(const string& strMultiFileName, TreeNode& trSetting)
{
	StringArray vsFileNames;
	separate_multiline_files(strMultiFileName, vsFileNames); 

	return _construct_GUI_tree(trSetting, vsFileNames);
}


static bool file_name_event(TreeNode& trGetN, string& strErrMsg, bool bClearSetting = true)
{
	string strFileName = trGetN.fname.strVal;
	TreeNode trNode = trGetN.trfiles;

	if ( bClearSetting )
		trNode.RemoveChildrenWithPrefix();

	if ( !construct_tree_setting(strFileName, trNode) )
	{
		trNode.RemoveChildrenWithPrefix();
		strErrMsg = CER_INVALID_IMPORT_DATA_FILE;
		return false;
	}

	return true;
}




void impSIE(const string& fname, const TreeNode& trfiles, const TreeNode& options, Range& orng, TreeNode& trheader, const int& reimp)
{
	
	int nRet = 0; 
	Tree trBaseInfo;
	
	WorksheetPage wp;
	Worksheet ws;
	
	int r1,r2,c1,c2; 
	Datasheet ds;
	
	if ( !GetRangeInfo(orng, ds, wp, c1, c2) )
		XF_THROW(XFERR_INVALID_RANGE);
	ws = ds;
	
	if(!ws)
		XF_THROW(CER_INVALID_WKS);
	
	TreeNode tnUsingFilter;
	int nVer;
	if ( fuGetDouble(options, IDE_DISP_IMP_ORIGINVER, nVer) )
		tnUsingFilter = options;
	
	int nFileImportMode = fuGetImportMode(tnUsingFilter);
	int nSparklines = fuGetSparkLine(tnUsingFilter);
	
	StringArray vsFileNames;
	separate_multiline_files(fname, vsFileNames);
	
	int nFileCount = vsFileNames.GetSize();
	if ( nFileCount <= 0 )
		XF_THROW(CER_INVALID_IMPORT_DATA_FILE);
	
	if ( trfiles.IsEmpty() && !fname.IsEmpty() )
	{
		if ( !construct_tree_setting(fname, trfiles) )
		{
			XF_THROW(CER_INVALID_IMPORT_DATA_FILE);
			return ;
		}
	}
	int nIndexLayer = wp.Layers.Count();
	
	int nFileIndex = 0;
	foreach(TreeNode trFileNode in trfiles.Children )
	{
		ws = GetTargetLayer(wp, nIndexLayer, nFileIndex, tnUsingFilter, true, orng, ASCIMP_MODE_NEW_BOOKS, c1, false, c2);
	
		SIEFile fileSIE(vsFileNames[nFileIndex++]);
		fileSIE.Import(tnUsingFilter, trFileNode, ws);
		
	}
	
}

//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 impSIE_event1(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	if( xf_is_extended_event(nEventID) )
		return impSIE_event1_ex(trGetN, nRow, nEventID, dwEnables, lpcszNodeName, DynaCntrlContainer, strAux, strErrMsg);
	DECLARE_BUTTON_ENABLES
	
	OK_SURE(bOKEnable);
	
	if ( GETNE_ON_INIT == nEventID || GETNE_ON_THEME == nEventID )
	{
		s_bFileValid = file_name_event(trGetN, strErrMsg, false);
		OK_SURE(bOKEnable);
		return true;
	}
	
	string strTagName = lpcszNodeName;
	if(strTagName == "fname")
	{
		s_bFileValid = file_name_event(trGetN, strErrMsg);
		OK_SURE(bOKEnable);
		return true;
	}
	
	return false;

}

int impSIE_make_tree(TreeNode& tr, LPCSTR lpcszVarName)
{
	
	string strTagName = lpcszVarName;
	
	if ( 0 == strcmp(lpcszVarName, "options") )
	{
		constructOptionsForXF(tr, false, false, true, false, false);
	
		/*
		TreeNode tr1stImportMode = tree_get_node_by_id(tr, IDE_DISPIMP_1STMODE, true);
		if ( tr1stImportMode )
		{
			string strCombo, strMapping;
			strCombo = getImportModeListString(strMapping, SIE_1ST_FILE_IMPORT_MODE_LIST);
			tr1stImportMode.SetAttribute(STR_COMBO_ATTRIB, strCombo);
			tr1stImportMode.SetAttribute(STR_INTMAP_ATTRIB, strMapping);
			tr1stImportMode.nVal = ASCIMP_MODE_REPLACE_DATA;
		}
		
		TreeNode trImportMode = tree_get_node_by_id(tr, IDE_IMP_IMPORTMODE, true);
		if ( trImportMode )
		{
			string strCombo, strMapping;
			strCombo = getImportModeListString(strMapping, SIE_IMPORT_MODE_LIST);
			trImportMode.SetAttribute(STR_COMBO_ATTRIB, strCombo);
			trImportMode.SetAttribute(STR_INTMAP_ATTRIB, strMapping);
			trImportMode.nVal = ASCIMP_MODE_NEW_SHEETS;
		}
		*/
	
		fuSetShowTime(tr, 0);
		fuSetXFunctionName(tr, "impSIE");
		
		// Add user parameters checkbox
		TreeNode trTemp = tr.AddNode("UserParamChan");
		trTemp.SetAttribute(STR_LABEL_ATTRIB, _L("Add extra rows for channel parameters"));
		trTemp.ID = TRGP_CHECK;
		trTemp.DataID = GET_USER_DATAID(1);
		trTemp.nVal = 0;
		
		// Add user parameters checkbox
		trTemp = tr.AddNode("UserParam");
		trTemp.SetAttribute(STR_LABEL_ATTRIB, _L("Add extra rows for dimension parameters"));
		trTemp.ID = TRGP_CHECK;
		trTemp.DataID = GET_USER_DATAID(2);
		trTemp.nVal = 1;
	
		return 0;
	}
	
	if ( strTagName == "trfiles" )
	{
		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 impSIE_before_execute(TreeNode& trGetN, int nGetNDialog, int& nRet, int dwCntrl)
{
	
	if(nGetNDialog > 0)
	{
		string strFile = trGetN.fname.strVal;
		if(strFile == "fname$")
			trGetN.fname.strVal = "";
	
		trGetN.trheader.Show = 0;
		if(1 == trGetN.reimp.nVal)
		{
			trGetN.fname.Enable = 2;
			trGetN.orng.Enable = 2;
			trGetN.trfiles.Enable = 2;
		}
	
	}
	
	if(nGetNDialog >= 0)
	{
	
		if ( LTXF_FROM_GUI_MENU == dwCntrl )
			trGetN.fname.strVal = "";
	}
	
	if(nGetNDialog > -1)
	{
		bool bResetFileInfo = false; ///---Sim 03-24-2009 QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION
		
		string strFileName = trGetN.fname.strVal;
	
		if ( LTXF_FROM_GUI_MENU & dwCntrl )
			strFileName = "";
	
		if(is_empty_or_unassigned(strFileName))
		{			
			int nFilesRet;
			if ( 0 != nGetNDialog )
			{
				int nShowOptionsDlg = 1;
				nFilesRet = get_open_box_by_file_group(strFileName, "SIE","SIE",
					OPENBOX_FLAG_MULTIFILES, NULL, NULL, STR_SHOW_OPT_DLG, &nShowOptionsDlg);
				nRet = (nShowOptionsDlg ? XFEVT_PROCEED : XFEVT_PROCEED_NO_DLG);
			}
			else
			{
				nFilesRet = get_open_box_by_file_group(strFileName, "SIE", "SIE", true);
			}
	
			if ( 0 == nFilesRet )
			{
				nRet = XFEVT_ABORT;
				return;
			}
			trGetN.fname.strVal = strFileName;
			bResetFileInfo = true; ///---Sim 03-24-2009 QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION
		} ///---Sim 03-24-2009 QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION			
	
		string strErrMsg;
		///---Sim 03-24-2009 QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION
		//if( !file_name_event(trGetN, strErrMsg) )
		if( !file_name_event(trGetN, strErrMsg, bResetFileInfo) )
		///---END QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION
		{
			int nErrMsg = atoi(strErrMsg);
			nRet = XFEVT_ABORT;
			warning_msg_box(nErrMsg, false, 'E');
			return;
		}
		///---Sim 03-24-2009 QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION			
		//}
		///---END QA80-13342 SUPPORT_OC_ACCESS_IMP_FILE_DATA_SELECTION
	}
	
	 
}
//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 impSIE_event1_ex(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	return false;
}
