#include "projectiongui.h"
#include "ui_projectiongui.h"

ProjectionGui::ProjectionGui(SandboxSetup *_setup, MonitorGui *_mg, QWidget *parent) :
    SubApp("Projection setup", "Error", parent),
    ui(new Ui::ProjectionGui)
{
    setup = _setup;
    mg = _mg;
    ui->setupUi(this);
    ui->lblFrame->setGeometry(0, 0, ui->fContainer->width(), ui->fContainer->height());
    ui->txtInstructions->setAlignment(Qt::AlignJustify);
    blueScreen = new QtFullScreen(mg->getResolution(), true, this);

    frameTimer = new QTimer(this);
    connect(frameTimer, &QTimer::timeout, this, &ProjectionGui::refreshFrame);
}

ProjectionGui::~ProjectionGui()
{
    delete frameTimer;
    delete blueScreen;
    delete ui;
}

void ProjectionGui::showEvent(QShowEvent *event){
    QWidget::showEvent(event);
    startCapture();
}

void ProjectionGui::closeEvent(QCloseEvent *event){
    QWidget::closeEvent(event);
}

void ProjectionGui::valideRoutine(){
    closeCapture();
}

void ProjectionGui::cancelRoutine(){
    closeCapture();
}

void ProjectionGui::refreshFrame(){
    setup->getCamera()->capture();
    cv::Mat rgb = setup->getCamera()->getColorFrame();

    QImage img = QImage((uchar *)rgb.data, (int)rgb.cols, (int)rgb.rows, static_cast<int>(rgb.step.buf[0]), QImage::Format_RGB888);
    QPixmap image = QPixmap::fromImage(img);

    ui->lblFrame->setPixmap(image);
}

void ProjectionGui::startCapture(){
    if(!cameraUsed){
        // open blue screen on the selected output
        setup->getCamera()->capture();
        cv::Mat rgb = setup->getCamera()->getColorFrame();
        cv::Size sz = rgb.size();
        cv::Mat blue = cv::Mat(sz.height, sz.width, CV_8UC3, cv::Scalar(0, 0, 255));
        cv::circle(blue, cv::Point(sz.width/2, sz.height/2), sz.height*2/100, cv::Scalar(255,0,0), CV_FILLED, 8,0);
        blueScreen->editGeometry(mg->getResolution());
        blueScreen->imShow(blue);
        cameraUsed = true;
        frameTimer->start(100);
    }
}

void ProjectionGui::closeCapture(){
    if(cameraUsed){
        cameraUsed = false;
        frameTimer->stop();
        blueScreen->close();
        ui->lblFrame->clear();
    }
}