#include "dialogexportusb.h"
#include "ui_dialogexportusb.h"

#include <QStorageInfo>

#include <QDebug>

#include <QThread>

#include <QProcess>

#include "mainwindow.h"

DialogExportUSB::DialogExportUSB(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogExportUSB)
{
    //setAttribute(Qt::WA_TranslucentBackground);
    //setWindowFlags(Qt::CustomizeWindowHint);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog | Qt::Popup);
    //setWindowFlags(Qt::FramelessWindowHint);


    ui->setupUi(this);

    ui->label_InfoUSB->setGeometry(90, 60, 430, 190);

    ui->label_InfoFile->hide();
    ui->label_InfoProgress->hide();
    ui->progressBar_File->hide();
    ui->progressBar_Progress->hide();


    m_nSyncCheckCount = 0;
    //done(QDialog::Accepted);
    ui->progressBar_Progress->setRange(0, 100);
    ui->progressBar_File->setRange(0, 100);

    ui->progressBar_File->setValue(0);
    ui->progressBar_Progress->setValue(0);

    ui->progressBar_Progress->setTextVisible(true);

    ui->progressBar_File->setTextVisible(true);

    ui->progressBar_File->setFormat("%v / %m File Exports");

    m_nTypeExport = 0;

    /*
    QString strInfo;

    CommonData* pCommonData = MainWindow::GetCommonData();
    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();
    pStrExternalDiskPath->clear();

    Mount();

    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {

       qDebug() << storage.rootPath();
       if (storage.isReadOnly())
           qDebug() << "isReadOnly:" << storage.isReadOnly();

       QString strName = storage.name();
       QString strDevice = storage.device();



       if(strDevice.contains("/dev/sd")==true)
       {
           QStringList strList;


           *pStrExternalDiskPath = storage.rootPath();

           //strList << "name:" << storage.name();
           //strList << "fileSystemType:" << storage.fileSystemType();
           //strList << "size:" << storage.bytesTotal()/1000/1000 << "MB";
           //strList << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";

           strInfo = QString("name: %1\r\nFieSystemType: %2\r\nFull Size: %3 MBytes\r\nAvailable Size: %4 MBytes\r\nSystem Path: %5").arg(storage.name()).arg((QString)storage.fileSystemType()).arg(storage.bytesTotal()/1000/1000).arg(storage.bytesAvailable()/1000/1000).arg(storage.rootPath());





           m_nStorageFreeSize = storage.bytesAvailable()/1000/1000;
           m_nStorageSize = storage.bytesTotal()/1000/1000;
       }





    }


    ui->label_InfoUSB->setText(strInfo);

    if(m_nStorageFreeSize>100)
    {
        ui->pushButton_Export->setEnabled(true);
        ui->pushButton_Cancel->setEnabled(true);
    }
    else
    {
        ui->pushButton_Export->setEnabled(false);
        ui->pushButton_Cancel->setEnabled(true);
    }

    */


    SThreadImageSave* pThread = MainWindow::GetCommonData()->GetThreadCaptureImage();
    connect(pThread, SIGNAL(SetProgressExportFile(int, int)), this, SLOT(SetProgressExportFile(int, int)));
    connect(pThread, SIGNAL(SetProgressExportPercent(quint64, quint64)), this, SLOT(SetProgressExportPercent(quint64, quint64)));
    connect(pThread, SIGNAL(SetProgressSync(bool)), this, SLOT(SetProgressSync(bool)));
    connect(pThread, SIGNAL(SetExportInit()), this, SLOT(SetExportInit()));
    connect(pThread, SIGNAL(SetExportComplete()), this, SLOT(SetExportComplete()));

    connect(this, SIGNAL(StartExport(int)), pThread, SLOT(StartExport(int)));
    connect(this, SIGNAL(StopExport()), pThread, SLOT(StopExport()));

    connect(&m_TimerSync, SIGNAL(timeout()), this, SLOT(SyncUpdate()));

    connect(&m_TimerDeferred, SIGNAL(timeout()), this, SLOT(OnDeferredInit()));

    connect(&m_Process, SIGNAL(finished(int)), this, SLOT(ProcessFinish(int)));
    connect(&m_Process, SIGNAL(readyReadStandardOutput()), this, SLOT(ProcessReadyReadStandardOutput()));
    connect(&m_Process, SIGNAL(readyReadStandardError()), this, SLOT(ProcessReadyReadStandardError()));

    m_TimerDeferred.setSingleShot(true);
    m_TimerDeferred.setInterval(100);
    m_TimerDeferred.start(100);

}

DialogExportUSB::~DialogExportUSB()
{
    SThreadImageSave* pThread = MainWindow::GetCommonData()->GetThreadCaptureImage();
    disconnect(pThread, SIGNAL(SetProgressExportFile(int, int)), this, SLOT(SetProgressExportFile(int, int)));
    disconnect(pThread, SIGNAL(SetProgressExportPercent(quint64, quint64)), this, SLOT(SetProgressExportPercent(quint64, quint64)));
    disconnect(pThread, SIGNAL(SetProgressSync(bool)), this, SLOT(SetProgressSync(bool)));

    disconnect(this, SIGNAL(StartExport(int)), pThread, SLOT(StartExport(int)));
    disconnect(this, SIGNAL(StopExport()), pThread, SLOT(StopExport()));

    disconnect(&m_TimerSync, SIGNAL(timeout()), this, SLOT(SyncUpdate()));
    delete ui;
}

void DialogExportUSB::on_pushButton_Cancel_clicked()
{
    StopExport();

    if(m_TimerSync.isActive()==true)
    {
        m_TimerSync.stop();
    }

    Umount();

    done(QDialog::Rejected);
}

void DialogExportUSB::on_pushButton_Export_clicked()
{

    m_nSyncCheckCount = 0;
    //done(QDialog::Accepted);

    ui->label_InfoUSB->hide();

    ui->label_InfoFile->show();
    ui->label_InfoProgress->show();
    ui->progressBar_File->show();
    ui->progressBar_Progress->show();

    ui->progressBar_Progress->setRange(0, 100);

    ui->progressBar_Progress->setTextVisible(true);

    ui->progressBar_File->setTextVisible(true);

    ui->progressBar_File->setFormat("%v / %m File Exports");

    update();

    StartExport(m_nTypeExport);

    return;

    int i=0;
    for(i=1 ; i<101 ; i++)
    {
        ui->progressBar_Progress->setValue(i);
        QThread::usleep(100*1000);

        update();
    }
}


void DialogExportUSB::SetProgressExportFile(int nProgress, int nTotal)
{
    ui->progressBar_File->setRange(1, nTotal);
    ui->progressBar_File->setValue(nProgress);

    QString strInfo;
    strInfo = QString("%1 / %2 File Exports").arg(nProgress).arg(nTotal);
    ui->progressBar_File->setFormat(strInfo);
}

void DialogExportUSB::SetProgressExportPercent(quint64 nProgress, quint64 nTotal)
{
    int nPercentage = (float)(100.0f*(float)nProgress/(float)nTotal);

    if(nPercentage>100)
    {
        nPercentage = 100;
    }

    ui->progressBar_Progress->setRange(1, 100);
    ui->progressBar_Progress->setValue(nPercentage);

    //ui->progressBar_Progress->setRange(1, nTotal);
    //ui->progressBar_Progress->setValue(nProgress);

    ui->progressBar_Progress->resetFormat();
}

void DialogExportUSB::SetProgressSync(bool bComplete)
{
    if(bComplete==false)
    {
        m_TimerSync.setInterval(300);
        m_TimerSync.start();

        //ui->label_InfoProgress->hide();
        //ui->progressBar_Progress->hide();

        //ui->label_InfoFile->setText("Export Sync");
        ui->label_InfoProgress->setText("Export Sync");

        ui->pushButton_Export->setDisabled(true);
        ui->pushButton_Export->hide();

        ui->pushButton_Cancel->setDisabled(true);

        ui->pushButton_Cancel->setGeometry(240, 310, 130, 40);
    }
    else
    {
        if(m_TimerSync.isActive()==true)
        {
            m_TimerSync.stop();

            //ui->progressBar_File->setFormat("Export Complete");
            //ui->progressBar_Progress->setFormat("Export Complete");
        }



    }
}

void DialogExportUSB::SyncUpdate()
{
    m_nSyncCheckCount++;

    m_nSyncCheckCount = m_nSyncCheckCount%10;

    QString strInfo;

    strInfo = " Export File Sync ";
    int i=0;
    for(i=0 ; i<m_nSyncCheckCount ; i++)
    {
        strInfo += ". ";
    }

    //ui->progressBar_File->setFormat(strInfo);
    ui->progressBar_Progress->setFormat(strInfo);
}

void DialogExportUSB::Mount()
{
    QProcess process1;
    QProcess process2;

    process1.setStandardOutputProcess(&process2);

    process1.start("echo 1");
#ifdef _PC
    process2.start("sudo -S mount -o uid=1000,gid=1000 /dev/sdb1 /home/birdhead/test");
#else
    process2.start("sudo -S mount -o uid=1000,gid=1000 /dev/sda1 /home/birdhead/test");
#endif
    process2.setProcessChannelMode(QProcess::ForwardedChannels);

    // Wait for it to start
    if(!process1.waitForStarted())
        return;

    bool retval = false;
    QByteArray buffer;
    // To be fair: you only need to wait here for a bit with shutdown,
    // but I will still leave the rest here for a generic solution
    while ((retval = process2.waitForFinished()))
    {
        buffer.append(process2.readAll());
    }


    process1.terminate();
    process2.terminate();

    process1.waitForFinished(100);
    process2.waitForFinished(100);

    process1.deleteLater();
    process2.deleteLater();

    buffer.clear();



    QString strInfo;

    CommonData* pCommonData = MainWindow::GetCommonData();
    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();
    pStrExternalDiskPath->clear();

    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {

       qDebug() << storage.rootPath();
       if (storage.isReadOnly())
           qDebug() << "isReadOnly:" << storage.isReadOnly();

       QString strName = storage.name();
       QString strDevice = storage.device();



       if(strDevice.contains("/dev/sd")==true)
       {
           QStringList strList;


           *pStrExternalDiskPath = storage.rootPath();

           //strList << "name:" << storage.name();
           //strList << "fileSystemType:" << storage.fileSystemType();
           //strList << "size:" << storage.bytesTotal()/1000/1000 << "MB";
           //strList << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";

           strInfo = QString("name: %1\r\nFieSystemType: %2\r\nFull Size: %3 MBytes\r\nAvailable Size: %4 MBytes\r\nSystem Path: %5").arg(storage.name()).arg((QString)storage.fileSystemType()).arg(storage.bytesTotal()/1000/1000).arg(storage.bytesAvailable()/1000/1000).arg(storage.rootPath());





           m_nStorageFreeSize = storage.bytesAvailable()/1000/1000;
           m_nStorageSize = storage.bytesTotal()/1000/1000;
       }





    }

    SetInfoString(strInfo);

    if(m_nStorageFreeSize>100)
    {
        SetExportEnable(true);
    }
    else
    {
        SetExportEnable(false);
    }

    /*
    ui->label_InfoUSB->setText(strInfo);

    if(m_nStorageFreeSize>100)
    {
        ui->pushButton_Export->setEnabled(true);
        ui->pushButton_Cancel->setEnabled(true);
    }
    else
    {
        ui->pushButton_Export->setEnabled(false);
        ui->pushButton_Cancel->setEnabled(true);
    }
    */
}

void DialogExportUSB::Umount()
{
    QProcess process1;
    QProcess process2;

    process1.setStandardOutputProcess(&process2);

    process1.start("echo 1");
    process2.start("sudo -S umount /home/birdhead/test");
    process2.setProcessChannelMode(QProcess::ForwardedChannels);

    // Wait for it to start
    if(!process1.waitForStarted())
        return;

    bool retval = false;
    QByteArray buffer;
    // To be fair: you only need to wait here for a bit with shutdown,
    // but I will still leave the rest here for a generic solution
    while ((retval = process2.waitForFinished()))
    {
        buffer.append(process2.readAll());
    }


    process1.terminate();
    process2.terminate();

    process1.waitForFinished(100);
    process2.waitForFinished(100);

    process1.deleteLater();
    process2.deleteLater();

    buffer.clear();
}


void DialogExportUSB::SetExportComplete()
{
    ui->progressBar_File->setFormat("Export Complete");
    //ui->progressBar_Progress->setFormat("Export Complete");
    ui->label_InfoProgress->hide();
    ui->progressBar_Progress->hide();

    ui->pushButton_Cancel->setDisabled(false);

    Umount();
}

void DialogExportUSB::SetExportInit()
{
    ui->progressBar_File->setFormat("");
    //ui->progressBar_Progress->setFormat("Export Complete");
    ui->label_InfoProgress->show();
    ui->progressBar_Progress->show();

    ui->pushButton_Cancel->setDisabled(false);
}


void DialogExportUSB::OnDeferredInit()
{
    QString strInfo;

    CommonData* pCommonData = MainWindow::GetCommonData();
    QString* pStrExternalDiskPath = pCommonData->GetExternalDiskPath();
    pStrExternalDiskPath->clear();

    Mount();

    /*
    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {

       qDebug() << storage.rootPath();
       if (storage.isReadOnly())
           qDebug() << "isReadOnly:" << storage.isReadOnly();

       QString strName = storage.name();
       QString strDevice = storage.device();



       if(strDevice.contains("/dev/sd")==true)
       {
           QStringList strList;


           *pStrExternalDiskPath = storage.rootPath();

           //strList << "name:" << storage.name();
           //strList << "fileSystemType:" << storage.fileSystemType();
           //strList << "size:" << storage.bytesTotal()/1000/1000 << "MB";
           //strList << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";

           strInfo = QString("name: %1\r\nFieSystemType: %2\r\nFull Size: %3 MBytes\r\nAvailable Size: %4 MBytes\r\nSystem Path: %5").arg(storage.name()).arg((QString)storage.fileSystemType()).arg(storage.bytesTotal()/1000/1000).arg(storage.bytesAvailable()/1000/1000).arg(storage.rootPath());





           m_nStorageFreeSize = storage.bytesAvailable()/1000/1000;
           m_nStorageSize = storage.bytesTotal()/1000/1000;
       }





    }


    SetInfoString(strInfo);

    if(m_nStorageFreeSize>100)
    {
        SetExportEnable(true);
    }
    else
    {
        SetExportEnable(false);
    }
    */
}


void DialogExportUSB::ProcessFinish(int nRet)
{

}

void DialogExportUSB::ProcessReadyReadStandardOutput()
{

}

void DialogExportUSB::ProcessReadyReadStandardError()
{

}

void DialogExportUSB::SetInfoString(QString strInfo)
{
    ui->label_InfoUSB->setText(strInfo);
}

void DialogExportUSB::SetExportEnable(bool bEnable)
{
    if(bEnable==true)
    {
        ui->pushButton_Export->setEnabled(true);
        ui->pushButton_Cancel->setEnabled(true);
    }
    else
    {
        //ui->pushButton_Export->setEnabled(false);
        //ui->pushButton_Cancel->setEnabled(true);

        ui->pushButton_Export->setDisabled(true);
        ui->pushButton_Export->hide();

        ui->pushButton_Cancel->setEnabled(true);

        ui->pushButton_Cancel->setGeometry(240, 310, 130, 40);
    }
}


void DialogExportUSB::reject()
{
    return;
}
