#include "cmcamdriver.h"
#include "cmcam.h"
#include "cpp/HalconCpp.h"
//using namespace Halcon;
#include "cmakepath.h"
CMCamDriver::CMCamDriver(const QString &name, int32_t id)
    :CCamDriver(name,id)
{

}

CMCamDriver::~CMCamDriver()
{

}

int32_t CMCamDriver::grab_image(int32_t camid, CMImage *pImageDest)
{
	CPreciseTime timer;
	timer.StartTime();
        CMCam* pcam=(CMCam*)FindChannel(camid);
        Q_ASSERT(pcam);
        Halcon::Hobject img,img1;
        static int iIndex=0;
        //QString name=QString::fromUtf8("Test1280X960.jpg");//.arg(iIndex)
		QString name=QString::fromUtf8("Test4000X3000.jpg");
        iIndex++;iIndex%=2;
        Halcon::read_image(&img,CMakePath::make_image_path(name).toLatin1().data());
        Halcon::convert_image_type ( img,&img1,"byte");

//        unsigned char image[800 * 600];
//        int r,c;
//        for (r=0; r<600; r++)
//        for (c=0; c<800; c++)
//        image[r * 800+c] = c % 255;
//        gen_image1(&img1,"byte",800,600,(long)image);

        Hlong width,height;
        //uint8_t * ptr;
        Hlong ptr;
        char typ[128];
        Halcon::get_image_pointer1(img1,&ptr,typ,&width,&height);

		QMutexLocker locker1(&pcam->m_imageContainer.mutex);
        bool bFold=pcam->m_Variants.get_VData(Var_Cam_Image_Fold)->toBool();
        if(bFold)
        {
            width/=2;height/=2;
        }
        if(width!=(long)pcam->m_Variants.get_VData(Var_Cam_Width_ID)->toInt()||
                height!=(long)pcam->m_Variants.get_VData(Var_Cam_Height_ID)->toInt())
        {
            if(pcam->m_pRawImageData) delete [] pcam->m_pRawImageData;
            pcam->m_pRawImageData=new uint8_t[height*width];
            pcam->m_Variants.get_VData(Var_Cam_Width_ID)->setValue(int(width));
            pcam->m_Variants.get_VData(Var_Cam_Height_ID)->setValue(int(height));
        }
        int iMirrortype=NO_MIRROR;
        uint iFilpytpe= pcam->m_Variants.get_VData(Var_Cam_Image_Filp)->toUInt();
        switch(iFilpytpe)
        {
            case 1:iMirrortype=MIRROR_H; break;
            case 2:iMirrortype=MIRROR_V; break;
            case 3:iMirrortype=MIRROR_VH; break;
            default:break;
        }
		//LOG(INFO)<<"Capture  Image Before";
		memcpy(pcam->m_pRawImageData, (uint8_t*)ptr, width*height);
        //memcpy_mirror(pcam->m_pRawImageData,
        //        ptr,
        //        width,height,
        //        iMirrortype,bFold);
		//LOG(INFO)<<"Capture  Image End";
    CCamDriver::grab_image(camid,pImageDest);
	//MqDebug() << "Grab Image RawData:"<<pcam->m_pRawImageData <<"DST:"<< pImageDest << endl;


	//MqDebug() << "Grab image" << timer.GetTime() << "s";
    return RTN_SUCCESS1;
}

