#include "dualcamgrabber.h"
#include <iostream>
#include <pylon/PylonIncludes.h>
#include <stitchimage.h>

void DualcamGrabber::run() {
  stop_request = false;
  size_t counter = 0;

  if (wrapper->isOpen()) {
      Pylon::CInstantCameraArray &cameras = wrapper->getCameraArray();
      wrapper->frameRate(static_cast<uint>(framerate));
      wrapper->exposureTime(exposure);
      wrapper->gain(gain);
      cameras.StartGrabbing();
      Pylon::CGrabResultPtr frame0, frame1;
      Pylon::CPylonImage leftImage;
      Pylon::CPylonImage rightImage;
      Pylon::CPylonImage stitchedImage;
      std::string errorMessage = "";

      while (cameras.IsGrabbing() && !stop_request) {
          MyImage *img = new MyImage();
          cameras[0].RetrieveResult( 5000, frame0, Pylon::TimeoutHandling_ThrowException );
          cameras[1].RetrieveResult( 5000, frame1, Pylon::TimeoutHandling_ThrowException );

          leftImage.AttachGrabResultBuffer( frame0 );
          rightImage.AttachGrabResultBuffer( frame1 );

          if (leftImage.IsValid() && rightImage.IsValid()) {
            try {
              StitchImage::StitchToRight(leftImage, rightImage, &stitchedImage, errorMessage);
              img->setFrame(stitchedImage);
              buffer->push(img);
            } catch(const std::exception& e) {
              std::cerr << e.what() << '\n';
            }
          }
          counter += 1;
      }
      cameras.StopGrabbing();
    }
}