#include "oitautoanalysis.h"
#include "global.h"
#include "logger.h"

OITAutoAnalysis::OITAutoAnalysis(QObject *parent) : QObject(parent)
{

}

void OITAutoAnalysis::analysis()
{
    if(!Global::_OITAutoAnalysisModeFlag){
        return;
    }

    //
    if(!Global::_currentCurveExperimentDataPtr){
        return;
    }

    if(Global::_currentCurveExperimentDataPtr->phaseIndex != 2){
        return;
    }

#if 0
    static Global::ExperimentData reachCoefficientData;
    static bool runTimeReachTheCoefficientFirstFlag = false;
    if(!runTimeReachTheCoefficientFirstFlag &&
            (Global::_currentCurveExperimentDataPtr->dataVtr.last().runTime
             > Global::_OITAutoAnalysisCoefficient)){
        runTimeReachTheCoefficientFirstFlag = true;
        reachCoefficientData = Global::_currentCurveExperimentDataPtr->dataVtr.last();
    }

    if(runTimeReachTheCoefficientFirstFlag){
        logde<<"phase index 1:"<<Global::_currentCurveExperimentDataPtr->phaseIndex;
        logde<<"phase index:"<<Global::_currentCurveExperimentDataPtr->dataVtr.last().phaseIndex;

        if(Global::_currentCurveExperimentDataPtr->dataVtr.last().dsc
                - reachCoefficientData.dsc > Global::_OITAutoAnalysisThreshold){
            double x1 = reachCoefficientData.runTime;
            double x2 = Global::_currentCurveExperimentDataPtr->dataVtr.last().runTime;
            emit sigExperimentStop(x1,x2);
        }
    }
#endif

    if(Global::_mode != Global::Mode::Experiment){
        return;
    }

    static Global::ExperimentData phase2FirstData;
    static bool phase2FirstDataRecordFlag = false;
    if(!phase2FirstDataRecordFlag){
        phase2FirstDataRecordFlag = true;
        phase2FirstData = Global::_currentCurveExperimentDataPtr->dataVtr.last();
    }else{
        Global::ExperimentData& ed = Global::_currentCurveExperimentDataPtr->dataVtr.last();

        if((ed.runTime > Global::_OITAutoAnalysisCoefficient)
                && (ed.dsc - phase2FirstData.dsc > Global::_OITAutoAnalysisThreshold)){
            //
//            double x1 = phase2FirstData.runTime;
            double x1 = ConDefaultXValue;
            double x2 = ed.runTime;
            emit sigExperimentStop(x1,x2);

            phase2FirstDataRecordFlag = false;
        }
    }
}
