#include "processcopydisk.h"
#include "src/frame/logger.h"
#include "src/po/translation.h"
#include "src/view/modaldialog.h"
#include "src/data/datacdrom.h"
#include "src/frame/signals.h"
#include "src/frame/auditlog.h"
#include <QFileInfo>
#include <kysdk/kysdk-system/libkysysinfo.h>
#include <QDebug>
ProcessCopyDisk::ProcessCopyDisk(void *src, void *des, QObject *parent) :
    ProcessBasic(parent),
    m_oSource(src),
    m_oDestination(des)
{
    LOGGER->registerName(this, _("PROCESS_CD"));
    m_oProcessName = _("Copy Disk");
    title(m_oProcessName);
    setRange(0, 100);
    setValue(0);
}

bool ProcessCopyDisk::prepare()
{
    DataCDROM *src;
    DataCDROM *des;
    QFileInfo f;
    QString sysid;

    m_oProcess->setProgram("/bin/bash");
    src = (DataCDROM *)m_oSource;
    m_oSrcDeviceBlock = src->device();
    m_iProgress = 0;

    if (sysid.isEmpty()) sysid = _("KylinOS");

    if (src->mediumType().startsWith("CD"))
        f.setFile("/bin/cdrecord");
    else
        f.setFile("/bin/growisofs");
    if (!f.exists() || !f.isExecutable())
    {
        error(_("There is no %1 program or %1 cannot execute."
                "Please check the cdrecord and growisofs is "
                "exists or not, and give the right permissions"
                ".%2 exiting...")
              .arg(f.absoluteFilePath())
              .arg("KylinBurner"));
        return false;
    }

    des = static_cast<DataCDROM *>(m_oDestination);
    m_oDesDeviceBlock = des->device();
    g_user_signal->setDeviceBusyStatus(m_oSrcDeviceBlock,true);
    g_user_signal->setDeviceBusyStatus(m_oDesDeviceBlock,true);

    PROGRESS;
    MODAL->show();
    connect(this, SIGNAL(cancel(bool)), MODAL, SLOT(cancelEnable(bool)));

    if (des->mediumType().startsWith("CD"))
    {
        m_oMkisofs = QString("genisoimage -r -R -J -joliet-long -no-pad -no-iso-translate ");
        m_oMkisofs.append(QString("-A \"%1\" ").arg(_("KylinBurner")));
        m_oMkisofs.append(QString("-p \"%1\" ").arg(src->settingPreparer()));
        setValue(++m_iProgress, m_oIcon, _("Preparer %1").arg(src->settingPreparer()));
        m_oMkisofs.append(QString("-P \"%1\" ").arg(src->settingPublisher()));
        setValue(++m_iProgress, m_oIcon, _("Publisher %1").arg(src->settingPublisher()));
        m_oMkisofs.append(QString("-copyright \"%1\" ").arg(src->settingCopyright()));
        setValue(++m_iProgress, m_oIcon, _("Copyright %1").arg(src->settingCopyright()));
        m_oMkisofs.append(QString("-V \"%1\" ").arg(src->settingVolumnID()));
        setValue(++m_iProgress, m_oIcon, _("Volumn ID %1").arg(src->settingVolumnID()));
        m_oMkisofs.append(QString("%1").arg(src->mediumMountPoint()));
        if (src->settingSpeed())
            m_oCdrecord = QString("cdrecord -v driveropts=burnfree -nopad -eject dev=%1 speed=%2 ").arg(des->device()).arg(src->settingSpeed());
        else
            m_oCdrecord = QString("cdrecord -v driveropts=burnfree -nopad -eject dev=%1 ").arg(des->device());
        if (src->mediumStatus() == DataMedium::MEDIUM_INCOMPLETE)
            m_oCdrecord.append("-multi -");
        else
            m_oCdrecord.append("-");
        m_oArguments << "-c" << QString("%1 | %2").arg(m_oMkisofs).arg(m_oCdrecord);
    }
    else
    {
        m_oProcess->setProgram(f.fileName());
        m_oArguments << "-J" << "-r" << "-R" << "-joliet-long" << "-no-iso-translate"
                     << "-gui" << "-v" << "-ldots" << "-no-split-symlink-fields"
                     << "-no-cache-inodes" << "-full-iso9660-filenames";
        m_oArguments << "-A" << _("KylinBurner");

        m_oArguments << "-V" << src->settingVolumnID().trimmed();
        debug(_("Volumn ID : %1").arg(m_oArguments.last()));
        setValue(++m_iProgress, m_oIcon, _("Volumn ID %1").arg(m_oArguments.last()));
        m_oArguments << "-p" << src->settingPreparer().trimmed();
        debug(_("Preparer : %1").arg(m_oArguments.last()));
        setValue(++m_iProgress, m_oIcon, _("Preparer %1").arg(m_oArguments.last()));
        m_oArguments << "-P" << src->settingPublisher().trimmed();
        debug(_("Publisher : %1").arg(m_oArguments.last()));
        setValue(++m_iProgress, m_oIcon, _("Publisher %1").arg(m_oArguments.last()));
        m_oArguments << "-copyright" << src->settingCopyright().trimmed();
        debug(_("Copyright : %1").arg(m_oArguments.last()));
        setValue(++m_iProgress, m_oIcon, _("Copyright %1").arg(m_oArguments.last()));
        if (src->mediumStatus() == DataMedium::MEDIUM_FINALIZED)
            m_oArguments << "-dvd-compat";
        m_oArguments << "-Z" << des->device();
        m_oArguments << src->mediumMountPoint();
    }

    return m_oKeep;
}

void ProcessCopyDisk::slotsOutput()
{
    qreal si;
    qreal t;
    qreal basic;
    QString output;
    QStringList s;

    output = m_oProcess->readAllStandardOutput();

    basic = 99 - m_iProgress;

    if (output.contains("Performing OPC"))
    {
        setValue(++m_iProgress, m_oIcon, _("Performing OPC"));
        cancel(false);
    }
    if (output.startsWith("\rTrack"))
    {
        s = output.split(" ");
        for (int i = 0; i < s.size(); ++i)
        {
            if (s.at(i).isEmpty())
            {
                s.takeAt(i);
                --i;
            }
        }
        si = s.at(2).toDouble();
        t = s.at(4).toDouble();
        if (s.size() > 5)
        {
            setValue(m_iProgress + si / t * basic, m_oIcon,
                     _("Writing track %1 speed %2 written %3 %4.")
                     .arg(s.at(1)).arg(s.last()).arg(s.at(2)).arg(s.at(3)));
        }
    }

    if (output.contains("Fixating"))
        setValue(99, m_oIcon, _("Fixating(Will wait minutes)"));
    if (output.contains("Input/output error"))
        m_oKeep = false;
}

void ProcessCopyDisk::slotsError()
{
    qreal v;
    int basic;
    QString output;
    QStringList ss;

    output = m_oProcess->readAllStandardError();
    if (output.contains("OPC failed."))
        m_oKeep = false;
    if (output.contains("Input/output error"))
        m_oKeep = false;
    if (output.contains(":-("))
        m_oKeep = false;
    if (output.contains("FATAL:"))
        m_oKeep = false;
    if (output.contains("error"))
        m_oKeep = false;
    if (output.contains(":-?"))
        m_oKeep = false;
    if (output.contains(":-["))
        m_oKeep = false;


    basic = 99 - m_iProgress;
    cancel(false);

    if (output.contains("done, estimate"))
    {
        output = output.left(output.indexOf('%'));
        v = output.toDouble();
        v = (v / 100.00) * basic;
        m_iProgress += v;
        if (m_iProgress > 99) m_iProgress = 99;
        if (m_fSpeed > 0)
            setValue(m_iProgress, m_oIcon, _("Burning by speed %1x").arg(m_fSpeed));
    }
    if (output.contains("Current Write Speed"))
    {
        ss = output.split(" ");
        ss = ss.last().split("x");
        m_fSpeed = ss.first().toDouble();
    }

    if (output.contains("flushing cache"))
    {
        setValue(99, m_oIcon, _("flushing cache"));
    }
    if (output.contains("closing track"))
    {
        setValue(99, m_oIcon, _("closing track"));
    }
    if (output.contains("closing session"))
    {
        setValue(99, m_oIcon, _("closing session"));
    }
    error(output);
}

void ProcessCopyDisk::slotsFinished(int errCode, QProcess::ExitStatus status)
{
    bool m_isSpecialMachine;
   // m_isSpecialMachine=kdk_system_is_zyj();
    auditburner=new QGSettings("org.ukui.kylinburner");
    auditlogpath="/var/log/kylin-burner/os_audit.log";
    m_isSpecialMachine=auditburner->get("burneraudit-isrunning").toBool();
    AuditLog copyDiskLog;
    DataCDROM *dest = (DataCDROM*)m_oDestination;
    g_user_signal->setDeviceBusyStatus(m_oSrcDeviceBlock,false);

 //   info(_("Exit code is %1, status : %2").arg(errCode).arg(status));
//    if (QProcess::NormalExit == status && 0 == errCode)
//    {
//        info( QString("slotsFinished() line[%1] : copy disk success.").arg(__LINE__) );
//    }
//    else
//    {
//        m_oKeep = false;
//        error( QString("slotsFinished() line[%1] : copy disk failure: %2").arg(__LINE__).arg(m_oProcess->errorString()) );
//    }
    info(_("Exit code is %1, status : %2").arg(errCode).arg(status));
    if ("cdrecord" == m_oProcess->program())
    {
        if (QProcess::NormalExit == status  && 0 == errCode)
        {
            info(QString("file:[%1] line:[%2] : slotsFinished() CD Medium copy disk success.").arg(__FILE__).arg(__LINE__));
            m_oKeep = true;
            qDebug()<<__LINE__<<__func__<<"ProcessCopyDisk"<<status;
        }
        else
        {
            error(QString("file:[%1] line:[%2] : slotsFinished() CD Medium failure in copy disk. [%3]").arg(__FILE__).arg(__LINE__).arg(m_oProcess->errorString()));
            m_oKeep = false;
            qDebug()<<__LINE__<<__func__<<"ProcessCopyDisk"<<status;
        }
    }
    else //DVD
    {
        if (QProcess::NormalExit != status  || errCode != 0)
        {
            m_oKeep = false;
            qDebug()<<__LINE__<<__func__<<"ProcessCopyDisk"<<status;
            error(QString("file:[%1] line:[%2] : slotsFinished() DVD Medium have error in copy disk. [%3]").arg(__FILE__).arg(__LINE__).arg(m_oProcess->errorString()));
        }
        else{
            qDebug()<<__LINE__<<__func__<<"ProcessCopyDisk"<<status;
            info(QString("file:[%1] line:[%2] : slotsFinished() DVD Medium copy disk success.").arg(__FILE__).arg(__LINE__));
            m_oKeep = true;
        }
        }

    if(m_isSpecialMachine==true){
        auditburner->set("burner-os-auditlog-name",auditlogpath);
    copyDiskLog.outputCopyResult("", dest->display(), dest->mediumType(), m_oProcessName, true==m_oKeep);
    }else{
        auditburner->set("burner-os-auditlog-name","");
    }

}

ProcessCopyDisk::~ProcessCopyDisk()
{
}
