#include "MergePanel.h"
#include "ui_MergePanel.h"
#include <QDebug>

#include "ClickableLabel.h"

/// \fn MainWindow::MainWindow(QWidget *parent)
/// \~English
/// \brief Default Constructor for the MainWindow.
/// \~Spanish
/// \brief Constructor por defecto del MainWindow.
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Signal connections
    // Conexion de senales

    // Closes window with cmd + w
    // Cierra la ventana con cmd + w
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_W), this, SLOT(close()));
    // Opens a image with cmd + o
    // Abre una imagen con cmd + o
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_O), this, SLOT(on_btnSelectImage_clicked()));
    // Opens background image with cmd + n
    // Abre imagen de transfondo con cmd + n
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_N), this, SLOT(on_btnSelectBackground_clicked()));
    // Saves an image with cmd + s
    // Guarda una imagen con cmd + s
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_S), this, SLOT(on_btnSaveImage_clicked()));
    // Merges two images with cmd + m
    // Fuciona dos imagenes con cmd + m
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_M), this, SLOT(on_btnMergeImages_clicked()));
    // Makes the label clickable.
    // Hace el labelWidget cliqueable.
    connect(ui->lblOriginalImage, SIGNAL(Mouse_Pressed()), this, SLOT(Mouse_Pressed()));
    connect(ui->lblBackgroundImage, SIGNAL(Mouse_Pressed()), this, SLOT(Mouse_PressedBackground())) ;
}

/// \fn MainWindow::~MainWindow(QWidget *parent)
/// \~English
/// \brief Destructor for the MainWindow.
/// \~Spanish
/// \brief Destructor del MainWindow.
MainWindow::~MainWindow(){
    delete ui;
}

/// \fn void MainWindow::on_btnSelectImage_clicked()
/// \~English
/// \brief Display the file browsing window to load an image. (Green Background)
/// \~Spanish
/// \brief Despliega la ventana de busqueda de archivos para subir una imagen. (Trasfondo verde)
void MainWindow::on_btnSelectImage_clicked(){
    QString fname = QFileDialog::getOpenFileName(this, tr("Choose an image"), QDir::homePath());
        if (!fname.isEmpty()){
            QImage image(fname);
            if (image.isNull()){
                QMessageBox::information(this, tr("Choose an image"),tr("Cannot load %1.").arg(fname));
                return ;
            }
            originalImage=image;
        }
    ui->lblOriginalImage->setPixmap(QPixmap::fromImage(originalImage));
    ui->origSize->setText("Original Image Size: " + QString::number(originalImage.width()) + "x" +QString::number(originalImage.height()));
}

/// \fn void MainWindow::on_btnSelectBackground_clicked()
/// \~English
/// \brief Display the file browsing window to load a background image.
/// \~Spanish
/// \brief Despliega la ventana de busqueda de archivos para subir una imagen para el trasfondo.
void MainWindow::on_btnSelectBackground_clicked(){
    QString fname = QFileDialog::getOpenFileName(this, tr("Choose an image"), QDir::homePath());
        if (!fname.isEmpty()){
            QImage image(fname);
            if (image.isNull()){
                QMessageBox::information(this, tr("Choose an image"),tr("Cannot load %1.").arg(fname));
                return ;
            }
            backgroundImage=image;
        }
    ui->lblBackgroundImage->setPixmap(QPixmap::fromImage(backgroundImage));
    ui->bgSize->setText("Original Image Size: " + QString::number(backgroundImage.width()) + "x" +QString::number(backgroundImage.height()));
}

/// \fn void MainWindow::on_btnMergeImages_clicked()
/// \~English
/// \brief  Invokes the function that merges the green screen image with the background image,
/// then displays the merged image.
/// \~Spanish
/// \brief Invoca la funcion que fusional la imagen con transfondo verde con la imagen de transfondo,
/// entonces displiega la imagen fusionada.
void MainWindow::on_btnMergeImages_clicked(){
    if (originalImage.width() > backgroundImage.width() || originalImage.height() > backgroundImage.height()){
        originalImage = originalImage.scaled(backgroundImage.width(), backgroundImage.height(), Qt::KeepAspectRatio, Qt::FastTransformation) ;
    }
    mergedImage = backgroundImage;
    MergeImages(originalImage, backgroundImage, mergedImage, ui->thresholdSlider->value(),ui->ghostBox->isChecked(), ui->lblOriginalImage->x, ui->lblOriginalImage->y, ui->lblBackgroundImage->x, ui->lblBackgroundImage->y);
    ui->lblMergedImage->setPixmap(QPixmap::fromImage(mergedImage));

}

/// \fn void MainWindow::on_btnSaveImage_clicked()
/// \~English
/// \brief Displays the file browse window to choose the path to save
/// the merged image in the file system.
/// \~Spanish
/// \brief Despliega la ventana de busqueda de archivos para escoger un camino
/// guardar la imagen fusionada en el sistema de archivos.
void MainWindow::on_btnSaveImage_clicked(){
    if(!mergedImage.isNull()){
        QPixmap out = QPixmap::grabWidget(this,361,10,481,481);
        QString fname = QFileDialog::getSaveFileName(this, tr("Save Merged Image"), (""), tr("PNG (*.png)" ));
        mergedImage.save(fname, "PNG");
    }
}

/// \fn void MainWindow::Mouse_Pressed()
/// \~English
/// \brief Function that gets the coordinates of the image with the greenscreen.
/// \~Spanish
/// \brief Funcion que obtiene las coordenada de la imagen con el trasfondo verde.
void MainWindow::Mouse_Pressed(){
    if (!originalImage.isNull()){
        if (originalImage.height() < ui->lblOriginalImage->height())
               ui->lblOriginalImage->y = ui->lblOriginalImage->y * ui->lblOriginalImage->height()/originalImage.height();
        else
               ui->lblOriginalImage->y = ui->lblOriginalImage->y * originalImage.height()/ui->lblOriginalImage->height();
        if(originalImage.width() < ui->lblOriginalImage->width())
             ui->lblOriginalImage->x = ui->lblOriginalImage->x * ui->lblOriginalImage->width()/originalImage.width();
        else
            ui->lblOriginalImage->x = ui->lblOriginalImage->x * originalImage.width()/ui->lblOriginalImage->width();
        ui->origCoord->setText("Selected Coord: (" + QString::number(ui->lblOriginalImage->x) + ","+QString::number(ui->lblOriginalImage->y) + ")" );
    }
}

/// \fn void MainWindow::Mouse_Pressed()
/// \~English
/// \brief Function that gets the coordinaates of the image with the final background.
/// \~Spanish
/// \brief Funcion que obtiene las coordenada de la imagen con el trasfondo final.
void MainWindow::Mouse_PressedBackground(){
    if (!backgroundImage.isNull()){
        if (backgroundImage.height() < ui->lblBackgroundImage->height())
                ui->lblBackgroundImage->y = ui->lblBackgroundImage->y * ui->lblBackgroundImage->height()/backgroundImage.height();
        else
               ui->lblBackgroundImage->y = ui->lblBackgroundImage->y * backgroundImage.height()/ui->lblBackgroundImage->height();
        if(backgroundImage.width() < ui->lblBackgroundImage->width())
             ui->lblBackgroundImage->x = ui->lblBackgroundImage->x * ui->lblBackgroundImage->width()/backgroundImage.width();
        else
            ui->lblBackgroundImage->x = ui->lblBackgroundImage->x * backgroundImage.width()/ui->lblBackgroundImage->width();
        ui->backCoord->setText("Selected Coord: (" + QString::number(ui->lblBackgroundImage->x) + ","+QString::number(ui->lblBackgroundImage->y) + ")" );
    }
}

/// \fn void MainWindow::on_thresholdSlider_actionTriggered()
/// \~English
/// \brief Invokes the function that merges the green screen image with the background image.
/// \~Spanish
/// \brief Invoca la funcion que fusiona la imagen de trasfondo verde con la imagen del trasfondo final.
void MainWindow::on_thresholdSlider_actionTriggered(){
    if (originalImage.width() > backgroundImage.width() || originalImage.height() > backgroundImage.height())
        originalImage = originalImage.scaled(backgroundImage.width(), backgroundImage.height(), Qt::KeepAspectRatio, Qt::FastTransformation) ;
    mergedImage = backgroundImage;
    MergeImages(originalImage, backgroundImage, mergedImage, ui->thresholdSlider->value(), ui->ghostBox->isChecked(), ui->lblOriginalImage->x, ui->lblOriginalImage->y, ui->lblBackgroundImage->x, ui->lblBackgroundImage->y);
    ui->lblMergedImage->setPixmap(QPixmap::fromImage(mergedImage));
}

/// \fn void MainWindow::on_ghostBox_clicked()
/// \~English
/// \brief Funtion that invokes the thresholdSlider function and creates a
/// ghost version of the image with greenscreen background.
/// \~Spanish
/// \brief Funcion que invoca la funcion thresholdSlider y crea una version
/// fantasma de la imagen con el trasfondo verde.
void MainWindow::on_ghostBox_clicked(){
    on_thresholdSlider_actionTriggered();
}
