#include "dialogexportsamba.h"
#include "ui_dialogexportsamba.h"

#include <QStorageInfo>

#include <QDebug>

#include <QThread>

#include <QProcess>

#include "mainwindow.h"

DialogExportSamba::DialogExportSamba(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogExportSamba)
{
    //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");

    ui->pushButton_Retry->hide();

    m_nTypeExport = 1;

    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_Process1, SIGNAL(finished(int)), this, SLOT(Process1Finish(int)));
    //connect(&m_Process1, SIGNAL(readyReadStandardOutput()), this, SLOT(Process1ReadyReadStandardOutput()));
    //connect(&m_Process1, SIGNAL(readyReadStandardError()), this, SLOT(Process1ReadyReadStandardError()));

    //connect(&m_Process2, SIGNAL(finished(int)), this, SLOT(Process2Finish(int)));
    //connect(&m_Process2, SIGNAL(readyReadStandardOutput()), this, SLOT(Process2ReadyReadStandardOutput()));
    //connect(&m_Process2, SIGNAL(readyReadStandardError()), this, SLOT(Process2ReadyReadStandardError()));

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

    Umount();
}

DialogExportSamba::~DialogExportSamba()
{
    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 DialogExportSamba::on_pushButton_Cancel_clicked()
{
    StopExport();

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

    Umount();

    done(QDialog::Rejected);
}

void DialogExportSamba::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 DialogExportSamba::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 DialogExportSamba::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 DialogExportSamba::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->setEnabled(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 DialogExportSamba::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 DialogExportSamba::Mount()
{
    SetExportEnable(true);
    QString strInfo = "Ready to Export 'Shared Network'";

    ui->pushButton_Export->click();


    SetInfoString(strInfo);

    return;
    SambaClient* pSambaClient = MainWindow::GetCommonData()->GetSambaClient();
    //QString strInfo;

    bool bMount = pSambaClient->IsMount();

    /*
    if(bMount==false)
    {
        pSambaClient->Umount();
        pSambaClient->Mount();
    }


    bMount = pSambaClient->IsMount();
    */
    if(bMount==false)
    {
        SetExportEnable(false);
        //strInfo = m_strInfo;
        strInfo = "Check Your Network Server!!";
    }
    else
    {
        SetExportEnable(true);
        strInfo = "Ready to Export 'Shared Network'";

        ui->pushButton_Export->click();
    }

    SetInfoString(strInfo);


}

void DialogExportSamba::Umount()
{
    return;
    SambaClient* pSambaClient = MainWindow::GetCommonData()->GetSambaClient();

    //pSambaClient->Umount();
    /*
    if(m_bError==true)
    {
        return;
    }
    m_strInfo.clear();

    QProcess process1;

    process1.setStandardOutputProcess(&m_Process2);

    process1.start("echo 1");
    m_Process2.start("sudo -S umount /home/birdhead/samba");
    m_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 = m_Process2.waitForFinished()))
    {
        buffer.append(m_Process2.readAll());
    }


    m_Process2.close();
    if(m_Process2.isOpen()==true)
    {
        m_Process2.terminate();
    }



    process1.close();
    if(process1.isOpen()==true)
    {
        process1.terminate();
    }



    buffer.clear();

    if(m_bError==true)
    {
        SetInfoString(m_strInfo);
    }
    */
}


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

    Umount();

    ui->pushButton_Cancel->setEnabled(true);
    ui->pushButton_Cancel->click();
}

void DialogExportSamba::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 DialogExportSamba::OnDeferredInit()
{
    Mount();
}


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

void DialogExportSamba::SetExportEnable(bool bEnable)
{
    if(bEnable==true)
    {
        ui->pushButton_Export->setEnabled(true);
        ui->pushButton_Cancel->setEnabled(true);
        ui->pushButton_Retry->hide();
        ui->pushButton_Export->show();
    }
    else
    {
        ui->pushButton_Retry->show();
        ui->pushButton_Export->hide();
        //ui->pushButton_Export->setDisabled(true);
        //ui->pushButton_Export->hide();

        //ui->pushButton_Cancel->setEnabled(true);

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

/*
void DialogExportSamba::Process1Finish(int nRet)
{
    QByteArray buffer;
    buffer.append(m_Process1.readAll());

}

void DialogExportSamba::Process1ReadyReadStandardOutput()
{
    QByteArray buffer;
    buffer.append(m_Process1.readAllStandardOutput());

    m_strInfo = buffer.toStdString().c_str();
}

void DialogExportSamba::Process1ReadyReadStandardError()
{
    QByteArray buffer;
    buffer.append(m_Process1.readAllStandardError());

    m_strInfo = buffer.toStdString().c_str();

    m_bError = 1;
}

void DialogExportSamba::Process2Finish(int nRet)
{
    QByteArray buffer;
    buffer.append(m_Process2.readAll());

}

void DialogExportSamba::Process2ReadyReadStandardOutput()
{
    QByteArray buffer;
    buffer.append(m_Process2.readAllStandardOutput());

    m_strInfo = buffer.toStdString().c_str();
}

void DialogExportSamba::Process2ReadyReadStandardError()
{
    QByteArray buffer;
    buffer.append(m_Process2.readAllStandardError());

    m_strInfo = buffer.toStdString().c_str();

    if(m_strInfo.contains("not mounted")==false)
    {
        m_bError = 1;
    }
    else
    {

    }


}

*/

void DialogExportSamba::on_pushButton_Retry_clicked()
{
    SambaClient* pSambaClient = MainWindow::GetCommonData()->GetSambaClient();

    if(pSambaClient->IsMount()==false)
    {
        Umount();
        Mount();
    }

    if(pSambaClient->IsMount()==true)
    {
        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);

    }




}


void DialogExportSamba::reject()
{
    return;
}
