#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "definitions.h"

#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>

#include <opencv2/opencv.hpp>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->toolBox->setStyleSheet("QToolBox{ icon-size: 32px; }");


    FILTER_ENABLE=ui->checkBox_filtering->isChecked();
    SCALE_ENABLE=ui->checkBox_scale_colormap->isChecked();

    // el modo online no esta habilitado
    ONLINE_STATE=false;

    // find camera
    CAMERAID=0;

    // reset
    RESET=false;


    for(int ID=0;ID<8;ID=ID+1)
    {
        CAPTURE.open(ID);
        //for(int i=0;(!CAPTURE.isOpened())&&(i<10);i++)   cv::waitKey(10);

        if(CAPTURE.isOpened())
        {
            AddItem2QComboBox(ui->comboBox, "Camera "+QString::number(ID));
            CAPTURE.release();
        }
    }

    old_dirpath=QDir::currentPath();

    load_init_file();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::AddItem2QComboBox(QComboBox* combo, QString itemName)
{

    QIcon icon = QIcon(":/myimages/share/speckleonline/icons/camera.png");
    combo->addItem( icon, itemName );
}

void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    CAMERAID=index;
}


void MainWindow::on_pushButton_runonline_clicked()
{
    if(ONLINE_STATE==false)
    {
        int i=0;
        while((CAPTURE.isOpened()==false)&&(i<100))
        {
            CAPTURE.open(CAMERAID);
            i++;
        }

        if(CAPTURE.isOpened()==false)
        {
            qDebug()<<"Error open de camera with ID: "+QString::number(CAMERAID);
            return;
        }
        ////////////////////////////////////////////////////////

        ui->pushButton_runonline->setText("Stop online mode");
        ONLINE_STATE=true;

        // showing text of tsampling
        int CURRENTMS=(int)(1000.0/ui->spinBox_FPS->value());
        qDebug()<<"Tsampling (ms): "+QString::number(CURRENTMS);

        // showing text of type of process
        int process_type=ui->comboBox_type->currentIndex();
        qDebug()<<"Current process: "+QString::number(process_type);

        ////////////////////////////////////////////////////////

        // TIMER!!!!!
        OnlineTimer1.start_online(  ui->doubleSpinBox_lin0,
                                    ui->doubleSpinBox_col0,
                                    ui->doubleSpinBox_height,
                                    ui->doubleSpinBox_width,
                                    ui->spinBox_blur_size,
                                    ui->label_max_colormap,
                                    ui->label_pseudo_FPS,
                                    ui->label_max_value,
                                    &CAPTURE,
                                    CAMERAID,
                                    CURRENTMS,
                                    process_type,
                                    ui->spinBox_nbloks->value(),
                                    &FILTER_ENABLE,
                                    &SCALE_ENABLE,
                                    &RESET);

        ////////////////////////////////////////////////////////
        if(process_type==PROCESS_NO)
        {
            ui->checkBox_scale_colormap->setEnabled(false);
            ui->label_colormap->setEnabled(false);
        }
        ui->spinBox_FPS->setEnabled(false);
        ui->comboBox_type->setEnabled(false);
        ui->spinBox_nbloks->setEnabled(false);
        ui->comboBox->setEnabled(false);
        ui->pushButton_save_image_sequence->setEnabled(false);

    }
    else
    {
        ui->pushButton_runonline->setText("Run online");
        ONLINE_STATE=false;

        OnlineTimer1.stop_online();
        ui->checkBox_scale_colormap->setEnabled(true);
        ui->spinBox_FPS->setEnabled(true);
        ui->comboBox_type->setEnabled(true);
        ui->spinBox_nbloks->setEnabled(true);
        ui->label_colormap->setEnabled(true);
        ui->comboBox->setEnabled(true);
        ui->pushButton_save_image_sequence->setEnabled(true);

        ui->label_pseudo_FPS->setText("0 FPS");
        ui->label_max_value->setText("0 MAX");

        int i=0;
        while(CAPTURE.isOpened()&&i<1000)
        {
            qDebug()<<"closing camera please white ....";
            CAPTURE.release();
            //if(getWindowProperty("Online", cv::WND_PROP_AUTOSIZE) >= 0)
            //    cv::destroyWindow("Online");
            qDebug()<<"closing the 'Online' window ....";
        }
        if(CAPTURE.isOpened())
            qDebug()<<"Error closing the camera.";
        else
            qDebug()<<"[OK] camera closed!";
    }
}



void MainWindow::on_pushButton_reset_clicked()
{
    RESET=true;
}

void MainWindow::on_checkBox_scale_colormap_clicked(bool checked)
{
    SCALE_ENABLE=checked;
}

void MainWindow::on_checkBox_filtering_clicked(bool checked)
{
    FILTER_ENABLE=checked;
}

//////////////////////////////////////////////////////////////////////////

void MainWindow::WarningMessageBox(QString msg)
{
    QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setText(msg);
    msgBox->setWindowTitle(tr("Warning:"));
    msgBox->setIcon(QMessageBox::Warning);
    msgBox->setWindowModality(Qt::ApplicationModal);
    msgBox->exec();
}

void MainWindow::ErrorMessageBox(QString msg)
{
    QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setText(msg);
    msgBox->setWindowTitle(tr("Error!!!"));
    msgBox->setIcon(QMessageBox::Warning);
    msgBox->setWindowModality(Qt::ApplicationModal);
    msgBox->exec();
}
//////////////////////////////////////////////////////////////////////////

void MainWindow::on_pushButton_select_output_path_clicked()
{
    QString OutputFolder = QFileDialog::getExistingDirectory(0,
                                                             tr("Select Output Folder"),
                                                             old_dirpath);
    ui->lineEdit_output_path->setText(OutputFolder);
    old_dirpath=OutputFolder;

    save_init_file(OutputFolder);
}



void MainWindow::on_pushButton_save_image_sequence_clicked()
{
    QString OutputFolder = ui->lineEdit_output_path->text();

    if(OutputFolder.length()==0)
    {
        ErrorMessageBox(tr("The directory path is void."));
        return;
    }

    if(!QDir(OutputFolder).exists()) QDir().mkdir(OutputFolder);

    if(!QDir(OutputFolder).exists())
    {
        ErrorMessageBox(tr("Can't create the directory path: ")+OutputFolder);
        return;
    }
    else
    {
        // showing text of tsampling
        int CURRENTMS=(int)(1000.0/ui->spinBox_FPS->value());
        qDebug()<<"Tsampling (ms): "+QString::number(CURRENTMS);


        OfflineTimer1.start_online( ui->doubleSpinBox_lin0,
                                    ui->doubleSpinBox_col0,
                                    ui->doubleSpinBox_height,
                                    ui->doubleSpinBox_width,
                                    ui->statusBar,
                                    ui->spinBox_FPS,
                                    ui->comboBox,
                                    ui->toolBox,
                                    OutputFolder,
                                    &CAPTURE,
                                    CAMERAID,
                                    CURRENTMS,
                                    ui->spinBox_nimages->value());
    }

}

//////////////////////////////////////////////////////////////////////////

void MainWindow::load_init_file(void)
{
    QSettings settings("speckleonline","speckleonline");
    old_dirpath=settings.value("mydata/OldSaveDirectory",QDir::currentPath()).toString();
    qDebug()<<"Load init data from: "<<settings.fileName();
}

void MainWindow::save_init_file(QString OldSaveDirectory)
{
    QSettings settings("speckleonline","speckleonline");
    settings.beginGroup("mydata");
    settings.setValue("OldSaveDirectory",OldSaveDirectory);
    settings.endGroup();

    //qDebug()<<"Wrote init data in: ",settings.fileName();
}


void MainWindow::on_actionAbout_triggered()
{
    QString Texto=  tr("<b>Program:</b> ")+QString(APP_TARGET)+"<br>"+
                    tr("<b>Version:</b> ")+QString(APP_VERSION)+"<br>"+
                    tr("<b>Homepage:</b> <a href=\"")+
                    QString(STRING_HOMEPAGE)+tr("\">")+
                    QString(STRING_HOMEPAGE)+tr("</a><br>")+
                    tr("<b>Authors:</b> Fernando Pujaico Rivera, Roberto Alves Braga Jr.<br>")+
                    tr("<b>Description:</b> A graphic user interface program to image acquisition, ")+
                    tr("designed to work with the dynamic speckle phenomenon.");

    QMessageBox about;

    about.setText("<center><h1>"+QString(APP_TARGET)+"</h1></center>");
    about.setInformativeText(Texto);
    about.setStandardButtons(QMessageBox::Ok);
    about.setIconPixmap(QPixmap(":/myimages/share/speckleonline/icons/speckleonline.png"));
    about.setDefaultButton(QMessageBox::Ok);
    about.show();
    about.exec();

}
