#include "myofflinetimer.h"

#include <QDebug>
#include <QMessageBox>

MyOfflineTimer::MyOfflineTimer()
{
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(MySlot()));

    Toolbox=NULL;
    StatusBar=NULL;
    Nbloks=0;
    Count=0;

    ROI_LIN0=NULL;
    ROI_COL0=NULL;
    ROI_HEIGHT=NULL;
    ROI_WIDTH=NULL;

    COMBOBOXCAM=NULL;
    SPINFPS=NULL;
}


void MyOfflineTimer::MySlot()
{
    // contando o tempo
    current_time = (double)cv::getTickCount();
    double diff_time_ms=1000.0*(current_time-old_time)/cv::getTickFrequency();
    double current_time_ms=1000.0*(current_time-first_time)/cv::getTickFrequency();
    old_time=current_time;

    QTextStream out(&file_ms);
    out << current_time_ms <<"\t" << diff_time_ms << "\n";

    // se a camera nao estiver aberta então abro ela
    if(!(CAP->isOpened()))    CAP->open(ID);

    // esta é a variavel que contem a imagem.
    cv::Mat frame;
    // tirando a imagem
    if(CAP->isOpened())
    {
        (*CAP) >> frame; // capturo uma imagem

        int    nc=frame.cols;
        int    nr=frame.rows;
        double l0=ROI_LIN0->value()*nr/100.0;
        double c0=ROI_COL0->value()*nc/100.0;
        double h =ROI_HEIGHT->value()*(nr-l0)/100.0;
        double w =ROI_WIDTH->value()*(nc-c0)/100.0;
        cv::Rect roi((int)c0,(int)l0,(int)w,(int)h);
        //qDebug()<<" nc"<<nc<<" nr"<<nr;
        //qDebug()<<" l0"<<l0<<" c0"<<c0<<" h"<<h<<" w"<<w;
        frame = frame(roi);

        cv::Mat framegray8b;
        cv::cvtColor(frame,framegray8b,cv::COLOR_RGB2GRAY);

        QString filepath=QDir(Directory).filePath(QString::number(Count)+".bmp");
        QByteArray filepathByteArray=filepath.toLocal8Bit();

        cv::imwrite( filepathByteArray.constData(), framegray8b );
    }
    else
    {
        qDebug()<<"Error opening the cam with id: "+QString::number(ID);
        return;
    }
    Count=Count+1;

    if(Count>=Nbloks)
    {
        stop_online();
    }
}

void MyOfflineTimer::start_online(  QDoubleSpinBox *lin0,
                                    QDoubleSpinBox *col0,
                                    QDoubleSpinBox *height,
                                    QDoubleSpinBox *width,
                                    QStatusBar *statusBar,
                                    QSpinBox *spinfps,
                                    QComboBox *comboBoxCam,
                                    QToolBox *toolbox,
                                    QString directory,     // Diretorio onde se salvam as imagens
                                    cv::VideoCapture *cap, // Controlador de video
                                    int camid,             // O ID da camera que vou abrir
                                    int ms,                // O tempo de amostragem =1/Fs
                                    int nbloks)

{
    CAP=cap;
    ID=camid;

    Nbloks=nbloks;
    Count=0;

    StatusBar=statusBar;
    Toolbox=toolbox;
    Directory=directory;

    ROI_LIN0=lin0;
    ROI_COL0=col0;
    ROI_HEIGHT=height;
    ROI_WIDTH=width;

    SPINFPS=spinfps;
    COMBOBOXCAM=comboBoxCam;

    old_time = (double)cv::getTickCount();
    first_time = old_time;

    QString filepath=QDir(Directory).filePath("speckleonline.ms.time");

    file_ms.setFileName(filepath);
    if (!file_ms.open(QIODevice::WriteOnly))
    {
        QMessageBox::information(0, tr("Unable to open file"), file_ms.errorString());
        return;
    }

    Toolbox->setEnabled(false);
    SPINFPS->setEnabled(false);
    COMBOBOXCAM->setEnabled(false);

    StatusBar->showMessage(tr("Saving images, please white ..."),2*nbloks*ms);

    timer->start(ms);
}



void MyOfflineTimer::stop_online(void)
{
    timer->stop();

    if (file_ms.isOpen())  file_ms.close();

    CAP->release();
    Toolbox->setEnabled(true);
    SPINFPS->setEnabled(true);
    COMBOBOXCAM->setEnabled(true);
    StatusBar->showMessage(tr("All data was saved!"),5000);

    QMessageBox *msgBox = new QMessageBox(0);
    msgBox->setText(tr("All data was saved!"));
    msgBox->setWindowTitle(tr("Message:"));
    msgBox->setWindowModality(Qt::ApplicationModal);
    msgBox->exec();
}
