#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostInfo>
#include <QSettings>
#include <QDebug>
#include "fpgaflashxml.h"
#include "QG/qzip.h"
#include <QMessageBox>
#include <QDebug>

#define APP_NAME            "FpgaBeamMuUpBuilder"
#define APP_FILE_INI        "./grifo_beamupbuilder.ini"
#define APP_XML_TEMP        "./info.xml"
#define ERROR_STR           "Error into process"
#define FILE_ZIP_PREFIX     "FLASH_FPGA"
#define MODEL_1             "GOLDEN"
#define MODEL_2             "USER"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QCoreApplication::setOrganizationName("Leonardo");
    QCoreApplication::setOrganizationDomain("Leonardo.com");

    QHostInfo hi=QHostInfo::fromName(QHostInfo::localHostName());
    setWindowTitle(QString("Host: %1").arg(hi.hostName()));

    QStyle* st=QApplication::style();

    ui->tbFilePrimary->setIcon(st->standardIcon(QStyle::SP_FileIcon) );
    ui->tbFileSecondary->setIcon(st->standardIcon(QStyle::SP_FileIcon) );
    ui->btnCreateZipFile->setIcon(st->standardIcon(QStyle::SP_MediaPlay) );


    fileSelector.setObjectName("GrifoBeamUpBuilderFileSelector");
    fileSelector.setOption(QFileDialog::ReadOnly, true);

    fileSelector.setViewMode(QFileDialog::Detail);
    fileSelector.setNameFilters(
                QStringList()<<"Binary (*.bin)");

    connect(ui->tbFilePrimary, &QToolButton::clicked, this,
            [this](bool)
    {
        QString tmp=fileSelector.directory().absolutePath();
        fileSelector.setOption(QFileDialog::ReadOnly, true);
        fileSelector.setFileMode(QFileDialog::AnyFile);
        fileSelector.setDirectory(tmp);

        if (fileSelector.exec())
        {
            ui->leFilePrimary->setText(fileSelector.selectedFiles().at(0));
        }
    }
            );

    connect(ui->tbFileSecondary, &QToolButton::clicked, this,
            [this](bool)
    {
        QString tmp=fileSelector.directory().absolutePath();
        fileSelector.setOption(QFileDialog::ReadOnly, true);
        fileSelector.setFileMode(QFileDialog::AnyFile);
        fileSelector.setDirectory(tmp);

        if (fileSelector.exec())
        {
            ui->leFileSecondary->setText(fileSelector.selectedFiles().at(0));
        }
    }
            );



    progressBar = new QProgressBar(ui->statusBar);
    progressBar->setAlignment(Qt::AlignRight);
    progressBar->setMaximumSize(180, 19);
    ui->statusBar->addPermanentWidget(progressBar);
    progressBar->setValue(0);
    progressBar->hide();

    flashTargets = flashTargetClass::instance();


    if (flashTargets->readTargets())
    {
        QStringList list = flashTargets->getInfoLists();
        ui->cbTgt->addItems(list);
    }
    else
    {
        qDebug()<<"Error read targets file config!";
    }

    readConfig();
}

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

void MainWindow::readConfig()
{
    //general configuration of app

    QSettings s(APP_FILE_INI, QSettings::IniFormat);
    if ( s.status() == QSettings::NoError )
    {
        s.beginGroup("general");

        ui->cbTgt->setCurrentIndex(s.value("model", 0).toInt());
        ui->cbArea->setCurrentIndex(s.value("area", 1).toInt());
        //ui->cbModel->setCurrentIndex(s.value("model", 0).toInt());
        ui->leFilePrimary->setText(s.value("primary", "").toString());
        ui->leFileSecondary->setText(s.value("secondary", "").toString());
        lastOutputFolder = s.value("lastOutputFolder", "").toString();

        s.endGroup();
    }

}

void MainWindow:: writeConfig()
{
    QSettings s(APP_FILE_INI, QSettings::IniFormat);
    if ( s.status() == QSettings::NoError )
    {
        s.beginGroup("general");

        s.setValue("model", ui->cbTgt->currentIndex() );
        s.setValue("area", ui->cbArea->currentIndex() );
        s.setValue("primary",ui->leFilePrimary->text() );
        s.setValue("secondary",ui->leFileSecondary->text() );
        s.setValue("lastOutputFolder", lastOutputFolder);

        s.endGroup();

        s.sync();
    }
}

bool addFileToZip(QZipWriter* _zip, QString _file)
{
    QFile file(_file);
    if (!file.exists())
    {
        return false;
    }

    QFileInfo finfo(_file);

    file.open(QIODevice::ReadOnly);
    _zip->addFile(finfo.fileName(), file.readAll());
    file.close();

    return true;
}



void MainWindow::on_btnCreateZipFile_clicked()
{
    QFileDialog *dialog = new QFileDialog();

    dialog->setObjectName("Select output folder for zip file");
    dialog->setDirectory(lastOutputFolder);
    dialog->setViewMode(QFileDialog::List);
    dialog->setFileMode(QFileDialog::DirectoryOnly);
    //dialog->setOption(QFileDialog::ShowDirsOnly);

    if (!dialog->exec())
    {
        return;
    }

    lastOutputFolder = dialog->selectedFiles().at(0);

    progressBar->setValue(0);
    progressBar->show();
    ui->statusBar->showMessage("Create file in progress...");

    if (!QFile::exists(ui->leFilePrimary->text()))
    {
        qCritical()<<"File primary is not exists!";
        QMessageBox::information(0, ERROR_STR, "File primary is not exists!");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }

    if (!QFile::exists(ui->leFileSecondary->text()))
    {
        qCritical()<<"File secondary is not exists!";
        QMessageBox::information(0, ERROR_STR, "File secondary is not exists!");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }

    //extract tgt info
    targetItem tgt = flashTargets->getTarget(ui->cbTgt->currentIndex());

    fpagFlashXmlClass fpagFlashXml;
    fpagFlashXml.setTarget(tgt.idTgt);
    fpagFlashXml.setPrimary(ui->leFilePrimary->text());
    fpagFlashXml.setSecondary(ui->leFileSecondary->text());
    fpagFlashXml.setArea(ui->cbArea->currentIndex());            //only user flash region
    fpagFlashXml.setXmlFile(APP_XML_TEMP);

    if (!fpagFlashXml.writeXML())
    {
        qCritical()<<"XML not writed!";
        QMessageBox::information(0, ERROR_STR, "XML not writed!");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }
    else
    {
        qInfo()<<"XML is OK!";
    }

    //filename for zip
    //QString fileNameZip = "file_zip.zip";

    QString flash_area;

    if (ui->cbArea->currentIndex()==0)
    {
        flash_area = MODEL_1;
    }
    else
    {
        flash_area = MODEL_2;
    }

    QString fileNameZip = QString("%1_%2_%3.zip").arg(tgt.filePrefix).arg(flash_area).arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));

    QZipWriter zip(lastOutputFolder+"/"+fileNameZip);
    //zip.setCompressionPolicy(CompressionPolicy::NeverCompress);

    progressBar->setValue(30);
    if (!addFileToZip(&zip, ui->leFilePrimary->text()))
    {
        qCritical()<<"Primary NOT zipped";
        QMessageBox::information(0, ERROR_STR, "Primary NOT zipped");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }
    progressBar->setValue(60);
    if (!addFileToZip(&zip, ui->leFileSecondary->text()))
    {
        qCritical()<<"Secondary NOT zipped";
        QMessageBox::information(0, ERROR_STR, "Secondary NOT zipped");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }
    progressBar->setValue(90);
    if (!addFileToZip(&zip, APP_XML_TEMP))
    {
        qCritical()<<"XMP NOT zipped";
        QMessageBox::information(0, ERROR_STR, "XMP NOT zipped");
        ui->statusBar->showMessage("");
        progressBar->hide();
        return;
    }

    zip.close();

    progressBar->setValue(100);
    QMessageBox::information(0, APP_NAME, QString("File zip created: \n %1").arg(lastOutputFolder+"/"+fileNameZip));

    ui->statusBar->showMessage("");
    progressBar->setValue(0);
    progressBar->hide();
}
