#include <origin.h>
#include <GetNBox.h>
#include <xfutils.h>
/*
*	Jasmine 08/14/07 QA80-10207 REPORT_SHEET_CHECK_CONFLICT
*	Max 3/7/08 SHOULD_PASS_WHOLE_STRING_OF_LPCSZRDLABEL_FOR_LOCALIZATION
*	Echo 5/27/08 v8.0870 CORR_ENABLE_EMPTY_COL
*	Folger 12/18/08 QA80-12642 v8.0988 CONSISTENT_SHOW_LN_ONLY_IF_EXIST_FOR_HYPOTHESIS_TESTING_TOOLS
*	Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
*	Kyle 06/05/2009 QA70-13733 RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
*	Jacky 07/22/10 ORG-102 USER_CAN_SET_SIGNIFICANCE_LEVEL
*	Folger 08/26/2010 ORG-920-P1 ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA
*/

//put additional include files here
#include <GetNBox.h>
#include <report_utils.h>
#include <event_utils.h>
#include <stats_utils.h>
#include <o8dlg.h>
//put your own support static functions here


static void _get_ttest1_stats_to_vector(const tTestMean1SampleResults stTTStats, vector &vTTStats)
{
	vTTStats.SetSize(3);
	vTTStats[0] = stTTStats.tValue;
	vTTStats[1] = stTTStats.DOF;
	vTTStats[2] = stTTStats.Prob;	
	
}


void OneSampletTest(const Range& irng, const double& mean, const string& null, const int& tail, const double& alpha, const int& conf, const string& level, const int& actpower, const double& siglevel, const int& hypotpower, const string& hypotsize, const int& histogram, const int& box, ReportData& rd, ReportTree& rt)
{
	
	waitCursor junk;
	
	vector vData;
	DWORD dwRules = DRR_NO_WEIGHTS;
	DWORD dwPlotID;
	
	///Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	//int nErrCode = check_1_data(irng, true);
	int nMinSize;
	int nErrCode = check_1_data(irng, true, false, &nMinSize);
	///End DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	if (CER_NO_ERROR != nErrCode)
	{
		if (nErrCode == CER_COL_NUM_TOO_FEW_EX)
			XF_THROW_EX(nErrCode, 1)
		else
			XF_THROW(nErrCode);
	}
	///Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	if(nMinSize < 1)
	{
			XF_THROW(CER_NO_DATA);
	}
	///End DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	
	int nNumRanges = irng.GetNumData(dwRules);	
	
	string strMean = ftoa(mean);		///Kyle 06/05/2009 QA70-13733 RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
	
	vector<string> vstrLab(nNumRanges);
	vector vLevInGroup, vDataAll;
	vLevInGroup.SetSize(nNumRanges);
	string strFootNote;
	LPCSTR lpsczLabel = _L("One Sample t Test");
	report_tree_create(rt, lpsczLabel, "irng");	
	for (int ii = 0; ii < nNumRanges; ii++)
	{
		///------ Folger 12/18/08 QA80-12642 v8.0988 CONSISTENT_SHOW_LN_ONLY_IF_EXIST_FOR_HYPOTHESIS_TESTING_TOOLS
		//vstrLab[ii] =  range_get_col_name(irng, ii);
		vstrLab[ii] =  range_get_col_name(irng, ii, TRUE);
		///------ End CONSISTENT_SHOW_LN_ONLY_IF_EXIST_FOR_HYPOTHESIS_TESTING_TOOLS
		irng.GetData(dwRules, ii, &dwPlotID, NULL, &vData, NULL, NULL, NULL);
		
		/// Trim out missing values before calculation
		int nMissing = ocmath_count(NANUM, vData.GetSize(), vData);
		if (0 < nMissing)
			vData.Trim();
		
		///Echo 5/27/08 v8.0870 CORR_ENABLE_EMPTY_COL
		//if (vData.GetSize() == 0)
			//break; ///Echo 5/27/08 v8.0870 CORR_ENABLE_EMPTY_COL
		
		/// *** Descriptive Statistics
		DescStatOptions stStatsOpt;
		set_ttest_desc_stats_opt(stStatsOpt);
		
		DescStatResults stStatsRes;	
		nErrCode = stats_desc_stats(vData, stStatsOpt, stStatsRes);
		if (nErrCode != STATS_NO_ERROR)
		{
			XF_THROW_EX(CER_UNKNOWN_ERROR_EX, nErrCode);
		}
			
		rt_add_desc_stats(rt, &stStatsOpt, NULL, &stStatsRes, NULL, vstrLab[ii]);
			
		/// *****		One sample t Test		***** ///
		HypotTestOptions HTO;
		tTestMean1SampleResults tRes;
		HTO.HypotValue = mean;
		HTO.TailType=tail;
		nErrCode = ocmath_one_sample_t_test(vData, vData.GetSize(), &HTO, &tRes);
		if (nErrCode != STATS_NO_ERROR)
		{
			XF_THROW_EX(CER_UNKNOWN_ERROR_EX, nErrCode);
		}
		
		string strHYPT, strConclusion;
		int nHYPT, nConclusion, nConAccept, nConReject;
		switch (tail)
		{
			case TAILED_TEST_TWO:
			default:
				nHYPT = FOOTNOTE_TTEST1_TWO_TAIL;
				nConAccept = FOOTNOTE_TTEST1_CON_DIFF;
				nConReject = FOOTNOTE_TTEST1_CON_SAME;
				break;
			case TAILED_TEST_UPPER:
				nHYPT = FOOTNOTE_TTEST1_UPPER_TAIL;
				nConAccept = FOOTNOTE_TTEST1_CON_GRT;
				nConReject = FOOTNOTE_TTEST1_CON_NOT_GRT;
				break;
			case TAILED_TEST_LOWER:
				nHYPT = FOOTNOTE_TTEST1_LOWER_TAIL;
				nConAccept = FOOTNOTE_TTEST1_CON_LES;
				nConReject = FOOTNOTE_TTEST1_CON_NOT_LES;
				break;
		}
		ocu_load_err_msg_str(nHYPT, &strHYPT);
		///Kyle 06/05/2009 QA70-13733 RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
		//strHYPT.Format(strHYPT, mean, mean);
		strHYPT.Format(strHYPT, strMean, strMean);
		///End RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
		//--- Jacky 07/22/10 ORG-102 USER_CAN_SET_SIGNIFICANCE_LEVEL
		//nConclusion = (tRes.Prob<0.05) ? nConAccept : nConReject;
		nConclusion = (tRes.Prob< alpha) ? nConAccept : nConReject;
		//---end USER_CAN_SET_SIGNIFICANCE_LEVEL
		ocu_load_err_msg_str(nConclusion, &strConclusion);
		///Kyle 06/05/2009 QA70-13733 RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
		//strConclusion.Format(strConclusion, vstrLab[ii], mean);
		//--- Jacky 07/22/10 ORG-102 USER_CAN_SET_SIGNIFICANCE_LEVEL
		//strConclusion.Format(strConclusion, vstrLab[ii], strMean);
		strConclusion.Format(strConclusion, vstrLab[ii],alpha,strMean);
		//--- end USER_CAN_SET_SIGNIFICANCE_LEVEL
		///End RADIX_POINT_SHOULD_BE_COMMA_IN_GOS
		
		///Kyle 06/01/2009 ADD_NEW_LINE_CHARACTER_WITHOUT_REFERENCE_TO_THE_SUB_STRING
		//strFootNote += strConclusion;
		strConclusion.TrimRight("\r\n");
		if(!strFootNote.IsEmpty())
			strFootNote += "\r\n";
		strFootNote += strConclusion;
		///End ADD_NEW_LINE_CHARACTER_WITHOUT_REFERENCE_TO_THE_SUB_STRING
		
		vector vTTStats;
		_get_ttest1_stats_to_vector(tRes, vTTStats);
		
		rt_add_test_stats(rt, tail, vTTStats, strHYPT, strFootNote, vstrLab[ii]);
		
		if (conf)
		{
			vector vLevels, vPercents;
			int nLevels = level.GetTokens(vPercents);//put the confidence levels in vector
			vLevels = vPercents / 100.0;
			
			vector vLCLs, vUCLs;
			vLCLs.SetSize(nLevels);
			vUCLs.SetSize(nLevels);		
			
			nErrCode = ocmath_confidence_levels_for_mean(vLevels, vLevels.GetSize(), &tRes, vLCLs, vUCLs);
			if (nErrCode != STATS_NO_ERROR)
			{
				XF_THROW_EX(CER_UNKNOWN_ERROR_EX, nErrCode);
			}
			
			rt_add_conf_intvl(rt, vPercents, vLCLs, vUCLs, _L("Mean"), vstrLab[ii]);
		}
		
		if (actpower || hypotpower)
		{
			vector vSampleSizes, vPowers;
			int nSS = hypotsize.GetTokens(vSampleSizes);
			vPowers.SetSize(nSS + 1);
			
			vSampleSizes.InsertAt(0, vData.GetSize());
			
			nErrCode = stats_tTest_powers(siglevel, tail, vSampleSizes, tRes, vPowers);
			if (nErrCode != STATS_NO_ERROR)
			{
				XF_THROW_EX(CER_UNKNOWN_ERROR_EX, nErrCode);
			}
			
			rt_add_ttest_power(rt, siglevel, vSampleSizes, vPowers, actpower, hypotpower, vstrLab[ii]);
		}
		
		vLevInGroup[ii] = vData.GetSize();
		vDataAll.Append(vData);
	
	}
	
	if (rd)
	{
		
		ttest_update_report_data(rd, vDataAll,vLevInGroup,vstrLab);
		
		int nPlotType; 
		if (histogram) nPlotType += HYPO_TEST_HISTOGRAM;
		if (box) nPlotType += HYPO_TEST_BOX;
		
		hypo_test_rd_plotting(rd, vstrLab, nPlotType, rt);
	}
	
	
}

//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 OneSampletTest_event1(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	if( xf_is_extended_event(nEventID) )
		return OneSampletTest_event1_ex(trGetN, nRow, nEventID, dwEnables, lpcszNodeName, DynaCntrlContainer, strAux, strErrMsg);
	DECLARE_BUTTON_ENABLES
	/// Max 3/7/08 SHOULD_PASS_WHOLE_STRING_OF_LPCSZRDLABEL_FOR_LOCALIZATION
	//rd_set_optional(nEventID, bOKEnable, lpcszNodeName, trGetN.rd, trGetN.box.nVal||trGetN.histogram.nVal, "PlotData1");
	/// Max 4/8/08 move to event_utils.h
	//string strRDvalue = "[<input>]<new>";
	string strRDvalue = STR_DEFAULT_TEXT_FOR_REPORT_DATA_NODE;
	//------
	///------ Folger 08/26/2010 ORG-920-P1 ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA
	//okutil_convert_localized_PDS(&strRDvalue);
	//tr_set_optional(nEventID, lpcszNodeName, trGetN.rd, trGetN.box.nVal||trGetN.histogram.nVal, strRDvalue);
	tr_set_optional_ex(nEventID, lpcszNodeName, trGetN.rd, xf_event_is_change_param(trGetN), trGetN.box.nVal || trGetN.histogram.nVal);
	///------ End ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA
	/// END SHOULD_PASS_WHOLE_STRING_OF_LPCSZRDLABEL_FOR_LOCALIZATION
	
	///Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	//int nErrCode = check_1_data(trGetN.irng, true);
	int nMinSize;
	int nErrCode = check_1_data(trGetN.irng, true, false, &nMinSize);
	///End DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	if (nErrCode != CER_NO_ERROR)
	{
		bOKEnable = false;
		strErrMsg = nErrCode;
		if (nErrCode == CER_COL_NUM_TOO_FEW_EX)
			strErrMsg += ":" + 1;
	}
	///Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	else if(nMinSize < 1)
	{
		bOKEnable = false;
		strErrMsg = CER_NO_DATA;
	}
	///End DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
	///Jasmine 08/14/07 QA80-10207 REPORT_SHEET_CHECK_CONFLICT
	//return ttest_event(trGetN, bOKEnable, strErrMsg, _L("Mean"));	
	bool bRet = ttest_event(trGetN, bOKEnable, strErrMsg, _L("Mean"));	
	if(bOKEnable && is_same_sheet(trGetN.rd, trGetN.rt))
	{
		bOKEnable = false;
		nErrCode = XFERR_REPORT_SHEET_CONFLICT;
		strErrMsg = nErrCode;
	}
	return bRet;
	///End REPORT_SHEET_CHECK_CONFLICT

}

int OneSampletTest_make_tree(TreeNode& tr, LPCSTR lpcszVarName)
{
	
	return false;
	
}
//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 OneSampletTest_before_execute(TreeNode& trGetN, int nGetNDialog, int& nRet, int dwCntrl)
{
	
	//------ fisher 11/16/07 ADD_MAP_ID_TO_CHM
	if(is_use_origin_chm())
		trGetN.SetAttribute(STR_HELPID_ATTRIB, IDD_XF_OneSampletTest);
	
	if ((dwCntrl&LTXF_THEME_USED) && nGetNDialog <= 0)
	{
		bool bOKEnable; 
		string strErrMsg;
		ttest_event(trGetN, bOKEnable, strErrMsg, _L("Mean"));
		///Kyle 03/16/2009 DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
		//if (CER_NO_ERROR != check_1_data(trGetN.irng, true) ||  strErrMsg != "")
		int nMinSize;
		if (CER_NO_ERROR != check_1_data(trGetN.irng, true, false, &nMinSize) ||  strErrMsg != "" || nMinSize<1)
		///End DATA_SIZE_SHOULD_NOT_BE_LESS_THAN_1
			nRet = XFEVT_PROCEED_WITH_DLG;		
	}
	///Jasmine 08/14/07 QA80-10207 REPORT_SHEET_CHECK_CONFLICT
	if((-1 == nGetNDialog || 0 == nGetNDialog) && is_same_sheet(trGetN.rd, trGetN.rt))
	{
		nRet = XFEVT_ABORT;
		warning_msg_box(XFERR_REPORT_SHEET_CONFLICT, false, 'E');
	}
	///End REPORT_SHEET_CHECK_CONFLICT
}
//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 OneSampletTest_event1_ex(TreeNode& trGetN, int nRow, int nEventID, DWORD& dwEnables, LPCSTR lpcszNodeName, WndContainer& DynaCntrlContainer, string& strAux, string& strErrMsg)
{
	return false;
}
