#include "continuous_capture_thread.h"

continuous_capture_thread::continuous_capture_thread(){}

continuous_capture_thread::~continuous_capture_thread(){}

void continuous_capture_thread::run()
{
    int format;
    bool skip;
    long duration;
    QMutex mux;
    bool reduced = false;

    this->stopFlag = false;
    if(this->front_camera != nullptr && this->side_camera != nullptr){
        format = this->front_camera->get_Format_px();
        skip = false;
        duration = long(this->front_camera->get_Exposure_us()) *10;
    }else throw std::runtime_error("Cameras ARE NOT setted");

    //modify resolution??
    QMessageBox::StandardButton setDialog;
    setDialog = QMessageBox::question(nullptr, "", "Do you want to reduce resolution for better experience?",
                QMessageBox::Yes|QMessageBox::No);
     if (setDialog == QMessageBox::Yes) {
        reduced = true;
        this->front_camera->reduceResolution(4);
        this->side_camera->reduceResolution(4);
     }

    while(1){
        skip = false;
        std::future<camera::frame> futF_ = std::async(std::launch::async, [format, this]() { return front_camera->readImage(format,-1,true); });
        std::future<camera::frame> futS_ = std::async(std::launch::async, [format, this]() { return side_camera->readImage(format,-1,true); });
        if(futF_.wait_for(std::chrono::microseconds(long(duration)))==std::future_status::timeout)
            skip = true;
        if(futS_.wait_for(std::chrono::microseconds(long(duration)))==std::future_status::timeout)
            skip = true;

         camera::frame front_frame = futF_.get();
         camera::frame side_frame = futS_.get();

         if(!skip){
             //Convert from cv::Mat to QImage
             QImage front_image, side_image;
             QString front_tmp_path = "/tmp/frameF.png";
             QString side_tmp_path = "/tmp/frameS.png";
             cv::imwrite(front_tmp_path.toStdString(),front_frame.image);
             cv::imwrite(side_tmp_path.toStdString(),side_frame.image);
             front_image.load(front_tmp_path);
             side_image.load(side_tmp_path);

             //Emit frames
             emit ShowImages(front_image,side_image);
         }

         mux.lock();
         if(this->stopFlag){
            if(reduced){
                this->front_camera->reduceResolution(1);
                this->side_camera->reduceResolution(1);
            }
            break;
         }
         mux.unlock();

    }
}

void continuous_capture_thread::setFront(interfaceBALLUFF::Camera& camera)
{
    this->front_camera = &camera;
}

void continuous_capture_thread::setSide(interfaceBALLUFF::Camera& camera)
{
    this->side_camera = &camera;
}
