#include "cmwmanualmodel.h"
#include "ui_cmwmanualmodel.h"
#include "logic.h"
#include <cpp/HalconCpp.h>
#include "cmwcamlight.h"
#include "catest.h"
#include <QMessageBox>
//#include <QTimer>
CMWManualModel::CMWManualModel(QWidget *parent) :
    CMWidget(parent),
    ui(new Ui::CMWManualModel)
{
	ui->setupUi(this);
    if(m_gSystem.m_iMatchType==M_MATCHNCC)
    {
        m_pMtachForTest=new CAMatchNCC_H("matchfortest",0);
    }
    else if(m_gSystem.m_iMatchType==M_MATCHSHAPE)
    {
        m_pMtachForTest=new CAMatchShape_H("matchfortest",0);
    }
    else
    {
        Q_ASSERT(0);
    }
}

CMWManualModel::~CMWManualModel()
{
	delete m_pMtachForTest;
	m_pMtachForTest=0;
    delete ui;
}

void CMWManualModel::MInit()
{
    ui->widget_Model->MInit();
}

void CMWManualModel::MFresh()
{
	if(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X)
	{
		showShieldWindow(true,
					QObject::trUtf8("Switch to any cam."));
		return;
	}
	if(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B)
	{
		showShieldWindow(true,
					QObject::trUtf8("Switch to any side."));
		return;
	}
    showShieldWindow(false);
	ui->label_CAM_Name->setText(m_gSystem.m_mapNameList[m_iCurCamID]);
	ui->lblCamInfo->setText(m_gSystem.m_mapNameList[m_iCurCamID]);
	ui->label_SIDE_ID->setText(m_gSystem.m_mapNameList[m_iCurSideID]);
	CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
	MODEL_INFO& info=m_iCurCamID==CAM2X?
				pSide->lModels[0]:pSide->lModels[1];

    ui->lineEdit_miniScore->setText(QString::number(info.dMinScore));


    if(m_iCurCamID==CAM6X && m_gSystem.m_pMWCamLight6X)
    {
        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight6X;
        pCamLight->SetLight(info.iDirectLight,info.iSideLight);
		pCamLight->SetCamInfo(info.iExposureUs, info.iGain);
		ui->chkLowModelOffset->setEnabled(true);
    }

	if(m_iCurCamID==CAM2X && m_gSystem.m_pMWCamLight2X){
		CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight2X;
		pCamLight->SetLight(info.iDirectLight,info.iSideLight);
		pCamLight->SetCamInfo(info.iExposureUs, info.iGain);
		ui->chkLowModelOffset->setEnabled(false);
	}

    ui->widget_Model->m_pContainer->clearString( );
    loadModel();
    ui->widget_Model->refreshPixmap();

	CMWidget::MFresh();


    double templateoffsetX=pSide->m_Variants.get_VData(Var_ProductSide_TemplateOffsetX)
            ->toDouble();
    double templateoffsetY=pSide->m_Variants.get_VData(Var_ProductSide_TemplateOffsetY)
            ->toDouble();

	CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING, SM_MAIN, CProcess_Level);
	bool bEnableLowModel = pLevel->m_Variants.get_VData(Var_Process_ModelEnableLowOffset)->toInt()>0.1;
	if(m_iCurCamID == CAM2X && bEnableLowModel){
		if(m_iCurSideID == SIDE_A){
			templateoffsetX = pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideALowX)->toDouble();
			templateoffsetY = pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideALowY)->toDouble();
		}else if(m_iCurSideID == SIDE_B){
			templateoffsetX = pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideBLowX)->toDouble();
			templateoffsetY = pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideBLowY)->toDouble();
		}
	}

	ui->lineEdit_ModelOffsetX->setText(QString::number(templateoffsetX));
	ui->lineEdit_ModelOffsetY->setText(QString::number(templateoffsetY));

    ui->lineEdit_Contrast->setText(QString::number(info.iContrast));
	ui->chkLowModelOffset->setChecked(bEnableLowModel);
	
    bool benable=m_iCurCamID==CAM6X||(m_iCurCamID==CAM2X&&bEnableLowModel);
    ui->lineEdit_ModelOffsetX->setEnabled(benable);
    ui->lineEdit_ModelOffsetY->setEnabled(benable);
    //ui->pushButton_SetOffset->setEnabled(benable);
	//ui->btnToStreet->setEnabled(benable);
	/*if(!benable)
	ui->btnToModel->setEnabled(benable);*/

	ui->label_3->setVisible(false);
	ui->lineEdit_Contrast->setVisible(false);
	ui->label_4->setVisible(false);

	if(m_gSystem.IsSMAutoRun(SM_MAIN))
		setEnabled(false);
	else
		setEnabled(true);

	
}

void CMWManualModel::MApply()
{
	Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
	Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));

	CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
	MODEL_INFO& info=m_iCurCamID==CAM2X?
				pSide->lModels[0]:pSide->lModels[1];

	info.dMinScore=ui->lineEdit_miniScore->text().toDouble();

    if(m_iCurCamID==CAM6X && m_gSystem.m_pMWCamLight6X)
    {
        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight6X;
        pCamLight->GetLightData(info.iDirectLight,info.iSideLight);
        pCamLight->GetCamInfo(info.iExposureUs, info.iGain);
    }
	if(m_iCurCamID==CAM2X && m_gSystem.m_pMWCamLight2X)
	{
		CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight2X;
		pCamLight->GetLightData(info.iDirectLight,info.iSideLight);
        pCamLight->GetCamInfo(info.iExposureUs, info.iGain);
	}

	double templateoffsetX=ui->lineEdit_ModelOffsetX->text().toDouble();
	double templateoffsetY=ui->lineEdit_ModelOffsetY->text().toDouble();
	CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING, SM_MAIN, CProcess_Level);
	if(m_iCurCamID==CAM2X){
		if(m_iCurSideID == SIDE_A){
			pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideALowX)->setValue(templateoffsetX);
			pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideALowY)->setValue(templateoffsetY);

		}else if(m_iCurSideID == SIDE_B){
			pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideBLowX)->setValue(templateoffsetX);
			pLevel->m_Variants.get_VData(Var_ProductSide_TemplateOffsetSideBLowY)->setValue(templateoffsetY);
		}
	}

	if(m_iCurCamID==CAM6X){
		pSide->m_Variants.get_VData(Var_ProductSide_TemplateOffsetX)->setValue(templateoffsetX);
		pSide->m_Variants.get_VData(Var_ProductSide_TemplateOffsetY)->setValue(templateoffsetY);
	}

	pLevel->m_Variants.get_VData(Var_Process_ModelEnableLowOffset)->setValue(ui->chkLowModelOffset->isChecked());
}

void CMWManualModel::MTimeFresh()
{
    if( strCurFile!=m_gSystem.GetCurFile()||
			m_iCurCamID!=m_gSystem.m_iCurChID||
            m_iCurSideID!=m_gSystem.m_iCurSideID)
    {
        strCurFile=m_gSystem.GetCurFile();
		m_iCurCamID=m_gSystem.m_iCurChID;
        m_iCurSideID=m_gSystem.m_iCurSideID;

		ui->pushButton_SetOffset->setEnabled(false);
		ui->btnToStreet->setEnabled(false);
		ui->btnToModel->setEnabled(false);
        MFresh();
    }
}

void CMWManualModel::hideEvent(QHideEvent *event)
{
    CMWidget::hideEvent( event);
}


void CMWManualModel::loadModel()
{
    try
    {
		Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
		Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));

//		CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
//		QString modelpath= pSide->makeModelPath(m_iCurCamID);


        CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                           SM_MAIN,CProcess_Level);
        ModelData *pModelData=
                pLevel->GetModelData(m_iCurSideID,m_iCurCamID);

 //       m_pMtachForTest->loadModel(modelpath,pModelData);

        m_pMtachForTest->setModelData(pModelData);
        QString modelpath= m_gSystem.makeModelPath(m_gSystem.GetCurFile(),m_iCurSideID,m_iCurCamID);
		QFileInfo info(modelpath);
		ui->widget_Model->m_pContainer->addString(info.fileName());
        m_pMtachForTest->showmodel_xld(ui->widget_Model->m_pContainer);
        ui->widget_Model->setImage(pModelData->ModelImage);
    }
    catch(QString& s)
    {
        ui->widget_Model->m_pContainer->m_Image.resetImage();
        MqDebug()<<s;
    }

}


void CMWManualModel::on_pushButton_tool_clicked()
{
	Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
	Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));

	CCam* pCam=GET_CHDIRECT(m_iCurCamID,CCam);
	Q_ASSERT(pCam);
    int32_t width=pCam->m_Variants.get_VData(Var_Cam_Width_ID)->toInt();
    int32_t height=pCam->m_Variants.get_VData(Var_Cam_Height_ID)->toInt();
    if(!m_pMtachForTest->m_bModelRectInited)
    {
        m_pMtachForTest->m_bModelRectInited=true;
		m_pMtachForTest->model_rect=CRect(width/4,height/4,
										  CMPointd(width/2,height/2));
    }
    m_pMtachForTest->model_rect.m_center=CMPointd(width/2,height/2);
    m_pMtachForTest->model_rect.m_bCenterLocked=true;
    m_pMtachForTest->showragion_active(&pCam->m_imageContainer);

	//pCam->m_imageContainer.addShape(&m_pMtachForTest->m_rect_ROI,
	//	CImageContainer::ACTIVE_SHAPE);

    m_gSystem.m_bCamMove=false;

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Exe Morphology Sig"),
                          QVariantList()
                          <<CAM_DRIVER<<CCamDriver::EXE_MORPHOLOGY
                          <<m_iCurCamID<<m_gSystem.m_iMatchType,0);
    m_gSystem.start_test(SM_MAIN, msgqueue,false);
}

void CMWManualModel::on_pushButton_train_clicked()
{
    try
    {
		if(QMessageBox::Yes != QMessageBox::question(this, QObject::tr("Confirm"), 
			QObject::tr("Are you sure save parameter and train model?")))
		{
			return;
		}

        //qDebug()<<"Create model";
        ui->pushButton_train->setEnabled(false);
		ui->pushButton_train->blockSignals(true);

		QCoreApplication::processEvents();
		Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
		Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
		CCam* pCam=GET_CHDIRECT(m_iCurCamID,CCam);
        Q_ASSERT(pCam);
        CAMatch* pMatch=(CAMatch*)pCam->Find_Algorithm(m_gSystem.m_iMatchType);
        Q_ASSERT(pMatch);

        MApply();


        m_pMtachForTest->m_Variants=pMatch->m_Variants;
        CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
        MODEL_INFO& info=m_iCurCamID==CAM6X?
                    pSide->lModels[1]:pSide->lModels[0];

//        m_pCamLight->GetLightData(info.iDirectLight,info.iSideLight);
//        m_pCamLight->SetLight(info.iDirectLight,info.iSideLight);


        CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                           SM_MAIN,CProcess_Level);
        ModelData *pModelData=
                pLevel->GetModelData(m_iCurSideID,m_iCurCamID);

        m_pMtachForTest->m_Variants.get_VData(Var_Match_Contrast_ID)->setValue(info.iContrast);
        m_pMtachForTest->createModel(&pCam->m_imageContainer.m_Image,
                                     pModelData);

        m_pMtachForTest->showmodel_xld(ui->widget_Model->m_pContainer);
        ui->widget_Model->setImage(pModelData->ModelImage);

        Q_ASSERT(pLevel);

        CMWorkTableDriver* pWorkTableDriver=GET_CARD(WORKTABLE_DRIVER,
                                                     CMWorkTableDriver);
        Q_ASSERT(pWorkTableDriver);
        pWorkTableDriver->CurAxisToWt(m_iCurCamID,pLevel->m_ModelTestPos,true);
//        if(m_iCurCamID==CAM6X)
//        {
//            ui->pushButton_SetOffset->setEnabled(true);
//        }

        
        on_pushButton_save_clicked();
        if(pSide->m_bModelChanged)
            m_gSystem.m_SysMsg.SetMsg(tr("train model success"));

        //qDebug()<<"Create model success";
    }
    catch(QString& s)
    {
        m_gSystem.m_SysMsg.SetMsg(s, WARN_MSG_TYPE);
    }
	ui->pushButton_train->blockSignals(false);
    ui->pushButton_train->setEnabled(true);
}

void CMWManualModel::on_pushButton_test_clicked()
{

	if(QMessageBox::Yes != QMessageBox::question(this, QObject::tr("Confirm"), 
		QObject::tr("Are you sure save parameter and test?")))
	{
		return;
	}

	Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
	Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
    MApply();


    V_MsgQueue msgqueue;
    for(int i=0;i<1;i++)
    {
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Test Model Sig"),
                          QVariantList()
                          <<PROCESS_LEVELING<<CProcess_Level::TEST_MODEL
                          <<m_iCurSideID<<m_iCurCamID,0);

    }
    m_gSystem.start_test(SM_MAIN, msgqueue,false);

    if(m_iCurCamID==CAM6X)
    {
        //ui->pushButton_SetOffset->setEnabled(true);
		ui->btnToStreet->setEnabled(true);
		ui->btnToModel->setEnabled(true);
    }

	if(m_iCurCamID == CAM2X){
		ui->btnToStreet->setEnabled(true);
		ui->btnToModel->setEnabled(true);
	}
}

void CMWManualModel::on_pushButton_save_clicked()
{
    try
    {
        
		Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
		Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
		CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
        QString modelpath= m_gSystem.makeModelPath(m_gSystem.GetCurFile(),
                                                   m_iCurSideID,m_iCurCamID);

        CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                           SM_MAIN,CProcess_Level);

        pSide->m_bModelChanged = false;
        Q_ASSERT(pLevel);
        m_pMtachForTest->saveModel(modelpath,
                                  pLevel->GetModelData(m_iCurSideID,m_iCurCamID));
		pSide->m_bModelChanged=true;

    }
    catch(QString& s)
    {
        m_gSystem.m_SysMsg.SetMsg(s, WARN_MSG_TYPE);
    }
}

void CMWManualModel::on_pushButton_SetOffset_clicked()
{
	if(QMessageBox::Yes != QMessageBox::question(this, QObject::tr("Confirm"), 
		QObject::tr("Are you sure confirm street pos?")))
	{
		return;
	}

	CMPointd wt;
	CMWorkTableDriver* pWorkTableDriver=GET_CARD(WORKTABLE_DRIVER,
												 CMWorkTableDriver);
	Q_ASSERT(pWorkTableDriver);

    CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                       SM_MAIN,CProcess_Level);
    Q_ASSERT(pLevel);

    pWorkTableDriver->CurAxisToWt(m_iCurCamID,wt,true);

    ui->lineEdit_ModelOffsetX->setText(QString::number(pLevel->m_ModelTestPos.tX-wt.tX,'f',4));
    ui->lineEdit_ModelOffsetY->setText(QString::number(pLevel->m_ModelTestPos.tY-wt.tY,'f',4));

//    ui->pushButton_SetOffset->setEnabled(false);
}


void CMWManualModel::on_btnToModel_clicked()
{
    CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                       SM_MAIN,CProcess_Level);
    Q_ASSERT(pLevel);

    CMPointd wt;
    wt.tX = pLevel->m_ModelTestPos.tX;
    wt.tY = pLevel->m_ModelTestPos.tY;

    CMWorkTableDriver* pWorkTableDriver=GET_CARD(WORKTABLE_DRIVER,CMWorkTableDriver);
    Q_ASSERT(pWorkTableDriver);

    CMPointd axis;
    pWorkTableDriver->WtToAxis(m_iCurCamID, wt, axis);

    V_MsgQueue msgqueue;
    m_gSystem.absmove_xy_msg(axis.tX, axis.tY, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
}

void CMWManualModel::on_btnToStreet_clicked()
{
    double xOffset = ui->lineEdit_ModelOffsetX->text().toDouble(); //QString::number(pLevel->m_ModelTestPos.tX-wt.tX,'f',3));
    double yOffset = ui->lineEdit_ModelOffsetY->text().toDouble(); //QString::number(pLevel->m_ModelTestPos.tY-wt.tY,'f',3));
    CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
                                       SM_MAIN,CProcess_Level);
    Q_ASSERT(pLevel);

    CMPointd wt;
    wt.tX = pLevel->m_ModelTestPos.tX - xOffset;
    wt.tY = pLevel->m_ModelTestPos.tY - yOffset;

	CMWorkTableDriver* pWorkTableDriver=GET_CARD(WORKTABLE_DRIVER,CMWorkTableDriver);
	Q_ASSERT(pWorkTableDriver);

	CMPointd axis;
    pWorkTableDriver->WtToAxis(m_iCurCamID, wt, axis);

    V_MsgQueue msgqueue;
    m_gSystem.absmove_xy_msg(axis.tX, axis.tY, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
}

void CMWManualModel::on_btnFindModel_clicked()
{
    Q_ASSERT(!(m_iCurCamID!=CAM2X&&m_iCurCamID!=CAM6X));
    Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
    //MApply();


    V_MsgQueue msgqueue;
    for(int i=0;i<1;i++)
    {
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Test Model Sig"),
                          QVariantList()
                          <<PROCESS_LEVELING<<CProcess_Level::FINDMODEL_ONCE
                          <<m_iCurSideID<<m_iCurCamID,0);

    }
    m_gSystem.start_manual(SM_MAIN, msgqueue);

	if(m_iCurCamID==CAM6X || m_iCurCamID==CAM2X)
	{
		ui->pushButton_SetOffset->setEnabled(true);
		ui->btnToStreet->setEnabled(true);
		ui->btnToModel->setEnabled(true);
	}
    return;
 //   CATest* algorithmTest = new CATest("name", 0);

	//CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING,
	//	SM_MAIN,CProcess_Level);
 //   CCam* pCam2X=GET_CHDIRECT(CAM2X,CCam);
	//ModelData *pModelData= pLevel->GetModelData(m_iCurSideID,m_iCurCamID);

 //   /*algorithmTest->exe(&pModelData->ModelImage);
	//ui->widget_Model->setImage(pModelData->ModelImage);
	//ui->widget_Model->refreshPixmap();*/
	//algorithmTest->exe(&pCam2X->m_imageContainer.m_Image);
 //   algorithmTest->showragion(&pCam2X->m_imageContainer);
}

void CMWManualModel::on_chkLowModelOffset_clicked()
{

}
