#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <QProcess>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QTranslator>
#include <QDirIterator>
#include <QMessageBox>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QDesktopWidget *desktop = QApplication::desktop();

    int screenWidth, width;
    int screenHeight, height;
    int x, y;
    QSize windowSize;

    screenWidth = desktop->width(); // get width of screen
    screenHeight = desktop->height(); // get height of screen

    windowSize = size(); // size of our application window
    width = windowSize.width();
    height = windowSize.height();

    // little computations
    x = (screenWidth - width) / 2;
    y = (screenHeight - height) / 2;
    y -= 50;

    liveMedia.setPath("/lib/live/mount/medium");
    if (!liveMedia.exists()) {
        QDirIterator it("/lib/live/mount/persistence", QStringList() << "*.manifest", QDir::Files, QDirIterator::Subdirectories);
        while (it.hasNext()) {
            it.next();
	    if (it.fileName() == "filesystem.manifest") { // Ugly hack to detect usb drive because filesystem.manifest should be always there
	      liveMedia.setPath(it.filePath());
	      liveMedia.cdUp();
	      liveMedia.cdUp();
	      //qDebug() << liveMedia.absolutePath();
	      break;
	    }
        }
    }
    persistenceFile = liveMedia.absolutePath() + "/persistence";
    if (!liveMedia.exists("persistence")) {
        ui->delbtn->hide();
    }

    // move window to desired coordinates
    move ( x, y );
}

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

void MainWindow::on_createbtn_clicked()
{
    ui->statuslbl->setText(tr("Status: Working..."));
    system("kdesudo \"mount -o remount,rw " + liveMedia.absolutePath().toAscii() + "\"");
    int val = ui->spinBox->value(); // get the value
    if (liveMedia.exists("persistence")) {
        QMessageBox msgbox;
        msgbox.setText(tr("Found existing persistence image"));
        msgbox.setInformativeText(tr("Do you want to overwrite it?"));
        msgbox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgbox.setDefaultButton(QMessageBox::No);
        int ret = msgbox.exec();

        switch (ret) {
            case QMessageBox::Yes:
            {
                QString value1 = QString::number(val);  // convert int value to QString
                QString ddcmd = "sudo dd if=/dev/zero of=" + persistenceFile + " bs=1M count=";
                ddcmd = ddcmd + value1;
                QProcess *ddrun = new QProcess(this);  // Create new Process
                connect(ddrun, SIGNAL( finished ( int , QProcess::ExitStatus)), this, SLOT(statuscreate())); //connect finished signal to slot
                ddrun->start(ddcmd); // start process
                ui->createbtn->setEnabled(false);
                ui->delbtn->setEnabled(false);
                break;
            }
            case QMessageBox::No:
            {
                ui->statuslbl->setText(tr("Status:"));
                ui->createbtn->setEnabled(true);
                ui->delbtn->setEnabled(true);
                system("kdesudo \"sed -i 's/quiet/quiet persistence/g' " + liveMedia.absolutePath().toAscii() + "/syslinux.cfg\"");  //activate command for persistent should also work with existing persistence image.
                system("kdesudo \"sed -i 's/quiet/quiet persistence/g' " + liveMedia.absolutePath().toAscii() + "/boot/grub/grub.cfg\"");  //activate command for persistent should also work with existing persistence image.
		break;
            }
            default:
                break;
        }

    }
    else {
    QString value1 = QString::number(val);  // convert int value to QString
    QString ddcmd = "sudo dd if=/dev/zero of=" + persistenceFile + " bs=1M count=";
    ddcmd = ddcmd + value1;
    QProcess *ddrun = new QProcess(this);  // Create new Process
    connect(ddrun, SIGNAL( finished ( int , QProcess::ExitStatus)), this, SLOT(statuscreate())); //connect finished signal to slot
    ddrun->start(ddcmd); // start process
    ui->createbtn->setEnabled(false);  // Deactivate create Button
    // errorhandling ?
    //if (!ddrun.waitForFinished())
    //    QMessageBox::warning(this, "Creating Image failed!", "A problem occured creating the image file. Please check if you have write permissions in /tmp and enough free space.");
    //else
    //    ui->statuslbl->setText("Status: Image created successfully");
}
}

void MainWindow::statuscreate()
{
    ui->statuslbl->setText(tr("Status: Formatting..."));
    system("sudo /sbin/mkfs.ext4 -F " + persistenceFile.toAscii());
    system("mkdir /tmp/permnt");
    system("sudo mount " + persistenceFile.toAscii() + " /tmp/permnt");
    system("sudo bash -c \"echo '/ union' > /tmp/permnt/persistence.conf\"");
    system("sudo umount /tmp/permnt");
    system("kdesudo \"sed -i 's/quiet/quiet persistence/g' " + liveMedia.absolutePath().toAscii() + "/syslinux.cfg\"");
    system("kdesudo \"sed -i 's/quiet/quiet persistence/g' " + liveMedia.absolutePath().toAscii() + "/boot/grub/grub.cfg\"");  //activate command for persistent should also work with existing persistence image.
    ui->statuslbl->setText(tr("Status: Image created successfully"));
    ui->createbtn->setEnabled(true);
    ui->delbtn->show();
    ui->delbtn->setEnabled(true);
    QMessageBox msgbox2;
    msgbox2.setText(tr("Image created! You need to restart to activate persistence."));
    msgbox2.setInformativeText(tr("Do you want to restart?"));
    msgbox2.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgbox2.setDefaultButton(QMessageBox::Yes);
    int ret = msgbox2.exec();

    switch (ret) {
        case QMessageBox::Yes:
        {

            QString rebootcmd = "kdesudo reboot";
            QProcess *rebootrun = new QProcess(this);  // Create new Process
            rebootrun->start(rebootcmd); // start process
            break;
        }
        case QMessageBox::No:
        {
            break;
        }
        default:
            break;
    }
}

//void MainWindow::on_copybtn_clicked()
//{
//    // Code to copy image to usb drive. If usb drive is /live/image mount it rw
//    ui->statuslbl->setText(tr("Status: Working..."));
//    system("kdesudo \"mount -o remount,rw /live/image\"");
//    QProcess *cprun = new QProcess(this);
//    connect(cprun, SIGNAL( finished ( int , QProcess::ExitStatus)), this, SLOT(statuscopy()));
//    cprun->start("kdesudo cp /tmp/live-rw /live/image");
//
//}

//void MainWindow::statuscopy()
//{
//    system("kdesudo \"sed -i 's/quiet/quiet persistent/g' /live/image/syslinux.cfg\"");
//    ui->statuslbl->setText(tr("Status: Copied image successfully"));
//}


void MainWindow::on_delbtn_clicked()
{
    system("kdesudo \"sed -i 's/quiet persistence/quiet/g' " + liveMedia.absolutePath().toAscii() + "/syslinux.cfg\"");
    system("kdesudo \"sed -i 's/quiet persistence/quiet/g' " + liveMedia.absolutePath().toAscii() + "/boot/grub/grub.cfg\"");
    QMessageBox msgbox;
    msgbox.setText(tr("Deactivated Persistence. Click Create Image and don't overwrite the existing one to activate Persistence again."));
    msgbox.setStandardButtons(QMessageBox::Ok);
    msgbox.setDefaultButton(QMessageBox::Ok);
    int ret = msgbox.exec();
}
