#include "processburndata.h"
#include "src/frame/logger.h"
#include "src/po/translation.h"
#include "src/data/datacdrom.h"
#include "src/data/datadirectory.h"
#include "src/view/modaldialog.h"
#include "src/view/execdialog.h"
#include "src/frame/signals.h"
#include "src/model/diroptutils.h"

#include <QFileInfo>
#include <QDir>
#include <QCoreApplication>
#include <QStandardPaths>
#include <fstream>
#include <QDebug>

ProcessBurnData::ProcessBurnData(void *root, void *cdrom, QObject *parent) :
    ProcessBasic(parent),
    m_oFlag(false),
    m_bVerficationData(false),
    m_oProgressBarTimer_DVD(new QTimer(this))

{
    DataCDROM *c;
    m_bCreateISO = false;
    m_oCDROM = cdrom;
    cloneCDROM = ((DataCDROM *)cdrom)->clone();
    m_oRoot = root;
    m_root = (DataDirectory *)m_oRoot;
    m_odestination=m_root->destination();
    m_ototal=m_root->total();
    m_oSize=m_root->size();
    m_oNewSize = m_root->nSize()/1024.0/1024.0; // 单位：MB
    m_oDeviceBlock = cloneCDROM->device();
    //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();
    m_bVerficationData = cloneCDROM->settingVerficationData();

    qDebug() << __LINE__ << __func__ << "Verfication Data :" << m_bVerficationData;
    qDebug() << __LINE__ << __func__ << "ClossSession :" <<cloneCDROM->settingCloseSession() ;
    if (m_bVerficationData) {
        //拼接路径
        m_oTempPath = cloneCDROM->settingTempPath();
        if (m_oTempPath.endsWith("/")) {
            m_oTempPath = m_oTempPath + cloneCDROM->settingVolumnID();
        } else{
            m_oTempPath = m_oTempPath + '/' + cloneCDROM->settingVolumnID();
        }
    }

    m_fSpeed = 0;
    connect(m_oProgressBarTimer_DVD, SIGNAL(timeout()), this, SLOT(slotsProcessBarDVD()));
    connect(g_user_signal, &GlobalUserSignal::removeDisc, this, &ProcessBurnData::slotsRemoveDisc);

    if (cloneCDROM->mediumStatus() == DataMedium::MEDIUM_EMPTY)
    {
        LOGGER->registerName(this, _("PROCESS_BD"));
        title(_("Burning Data"));
        m_oProcessName = _("Burn Data");
        m_bAppendBurn = false;
    }
    else
    {
        LOGGER->registerName(this, _("PROCESS_AB"));
        title(_("Append Burning"));
        m_oProcessName = _("Append Burn");
        m_bAppendBurn = true;
    }
    MODAL->show();
    setRange(0, 100);
    setValue(0);
    g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,true);
}

bool ProcessBurnData::prepare()
{
    DataCDROM *cdrom;
    QFileInfo f;
    ifstream fin;
    std::string s;
    QString sysid;

    m_oISOOutput.clear();
    m_oProcess->setProgram("/bin/bash");
    cdrom = (DataCDROM *)m_oCDROM;

    m_iProgress = 0;
    fin.open("/etc/kylin-build");
    if (fin.is_open())
    {
        std::getline(fin, s);
        sysid = QString::fromStdString(s);
    }
    if (sysid.isEmpty()) sysid = _("KylinOS");

    if (cloneCDROM->mediumType().startsWith("CD"))
        f.setFile("/bin/cdrecord");
    else if (cloneCDROM->mediumType().contains("DVD+R DL"))
        f.setFile("/bin/xorriso");
    //    else if(cloneCDROM->mediumType().contains("DVD")&&cloneCDROM->settingCloseSession()==true)
    //        f.setFile("/bin/xorriso");
    else
        f.setFile("/bin/growisofs");
    if (!f.exists() || !f.isExecutable())
    {
        error(_("There is no %1 program or %1 cannot execute."
                "Please check the cdrecord, growisofs and xorriso is "
                "exists or not, and give the right permissions"
                ".%2 exiting...")
              .arg(f.absoluteFilePath())
              .arg("KylinBurner"));
        g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
        return false;
    }
    connect(this, SIGNAL(cancel(bool)), MODAL, SLOT(cancelEnable(bool)));
    m_bCreateISO = cloneCDROM->settingCreateISO();
    if (m_bCreateISO)
    {
        qDebug()<<__func__<<__LINE__<<m_bCreateISO;
        f.setFile("/bin/mkisofs");
        if (!f.exists() || !f.isExecutable())
        {
            error(_("There is no %1 program or %1 cannot execute."
                    "Please check the mkisofs is exists or not, and give "
                    "the right permissions.%2 exiting...")
                  .arg(f.absoluteFilePath())
                  .arg("KylinBurner"));
            g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
            return false;
        }
        m_oISOOutput = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
        m_oISOOutput.append("/").append(cloneCDROM->settingVolumnID()).append(".iso");
        f.setFile(m_oISOOutput);
        if (f.exists())
        {

            if (!EXEC->question(_("Create ISO") + " - " + _("Already Exists"),
                                _("There is already have the iso file named %1,"
                                  "replace it or not?").arg(f.fileName()))) {
                g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
                return false;
            }
            if (f.isFile()) QFile::remove(f.absoluteFilePath());
            else { QDir dir(f.absoluteFilePath()); dir.removeRecursively(); }
        }
    }
    PROGRESS;
    MODAL->show();
    m_oCreateISO = QString("mkisofs -o %1 -r -R -J -joliet-long -no-pad -no-iso-translate ").arg(m_oISOOutput);
    m_oMkisofs = QString("genisoimage -r -R -J -joliet-long -no-pad -no-iso-translate ");
    m_oMkisofs.append(QString("-A \"%1\" ").arg(_("KylinBurner")));
    m_oCreateISO.append(QString("-A \"%1\" ").arg(_("KylinBurner")));
    m_oArguments << "-c";
    if (cloneCDROM->mediumType().startsWith("CD"))
    {
        m_oCdrecord = QString("cdrecord -v driveropts=burnfree -nopad ");
        setValue(++m_iProgress, m_oIcon, _("Prepare to burn data to CD."));
    }
    else if (cloneCDROM->mediumType().contains("DVD+R DL"))
    {
        //m_oXorriso = QString("xorriso -dev %1 -map \"%2\" \"%3\" -volid \"%4\" -close off -commit -eject").arg(cloneCDROM->device()).arg(root->destination()).arg("/").arg(cloneCDROM->settingVolumnID());
        setValue(++m_iProgress, m_oIcon, _("Prepare to burn data to DVD+R."));
    }
    else
    {
        m_oGrowisofs = QString("growisofs -J -r -R -joliet-long -v -gui ");
        m_oGrowisofs.append(QString("-A \"%1\" ").arg(_("KylinBurner")));
        setValue(++m_iProgress, m_oIcon, _("Prepare to burn data to DVD."));
    }
    if (!sysid.isEmpty())
    {
        m_oMkisofs.append(QString("--sysid \"%1\" ").arg(sysid));
        m_oGrowisofs.append(QString("--sysid \"%1\" ").arg(sysid));
    }
    return m_oKeep;
}

bool ProcessBurnData::config()
{
    DataCDROM *cdrom;

    cdrom = (DataCDROM *)m_oCDROM;
    qDebug()<<__LINE__<<__func__<<cloneCDROM->settingCloseSession();
    if (cloneCDROM->mediumStatus() == DataMedium::MEDIUM_EMPTY)
    {
        m_oMkisofs.append(QString("-p \"%1\" ").arg(cloneCDROM->settingPreparer()));
        m_oCreateISO.append(QString("-p \"%1\" ").arg(cloneCDROM->settingPreparer()));
        m_oGrowisofs.append(QString("-p \"%1\" ").arg(cloneCDROM->settingPreparer()));
        m_oMkisofs.append(QString("-P \"%1\" ").arg(cloneCDROM->settingPublisher()));
        m_oCreateISO.append(QString("-P \"%1\" ").arg(cloneCDROM->settingPublisher()));
        m_oGrowisofs.append(QString("-P \"%1\" ").arg(cloneCDROM->settingPublisher()));
        m_oMkisofs.append(QString("-copyright \"%1\" ").arg(cloneCDROM->settingCopyright()));
        m_oCreateISO.append(QString("-copyright \"%1\" ").arg(cloneCDROM->settingCopyright()));
        m_oGrowisofs.append(QString("-copyright \"%1\" ").arg(cloneCDROM->settingCopyright()));
    }
    m_oMkisofs.append(QString("-V \"%1\" ").arg(cloneCDROM->settingVolumnID()));
    m_oCreateISO.append(QString("-V \"%1\" ").arg(cloneCDROM->settingVolumnID()));
    m_oGrowisofs.append(QString("-V \"%1\" ").arg(cloneCDROM->settingVolumnID()));
    if (cloneCDROM->settingSpeed())
    {
        m_oMkisofs.append(QString("-speed=%1 ").arg(cloneCDROM->settingSpeed()));
        m_oGrowisofs.append(QString("-speed=%1 ").arg(cloneCDROM->settingSpeed()));
        m_oCdrecord.append(QString("speed=%1 ").arg(cloneCDROM->settingSpeed()));
    }
    m_oCdrecord.append("-eject ");
    if (!cloneCDROM->settingCloseSession())
    {
        m_oCdrecord.append("-multi ");
    }
    else
        m_oGrowisofs.append("-dvd-compat ");

    setValue(++m_iProgress, m_oIcon, _("Prepare to start burn data."));
    return m_oKeep;
}

bool ProcessBurnData::working()
{
    DataCDROM *cdrom;
    //DataDirectory *root;

    cdrom = (DataCDROM *)m_oCDROM;
    //root = (DataDirectory *)m_oRoot;

    //if (root->size() > 2UL * 1024UL * 1024UL * 1024UL)
    if (m_oSize > 2UL * 1024UL * 1024UL * 1024UL)
    {
        debug(_("%1 data size more than 2 GB, need allow-limited-size "
                "extension").arg(_("CreateISO")));
        m_oMkisofs.append("-allow-limited-size ");
        m_oCreateISO.append("-allow-limited-size ");
        m_oGrowisofs.append("-allow-limited-size ");
    }
    //if (root->size() > 4UL * 1024UL * 1024UL * 1024UL)
    if (m_oSize > 4UL * 1024UL * 1024UL * 1024UL)
    {
        m_oMkisofs.append("-udf ");
        m_oCreateISO.append("-udf ");
        m_oGrowisofs.append("-udf ");
    }

    m_iCopied = 0;
    connect(m_root, SIGNAL(copied(QString,QString)), this, SLOT(slotsCopy(QString,QString)));
    //connect(root, SIGNAL(copied(QString,QString)), this, SLOT(slotsCopy(QString,QString)));
    m_root->copy();
    //m_ocopy;

    if (m_bVerficationData) {
        DirOptUtils *diropt  = new DirOptUtils;
        diropt->getFileListUnderDir1(m_oTempPath);
        diropt->testPrintMap();
        diropt->generateCheckFile();
        delete diropt;
    }

    m_oTimer->start(500);
    if (m_bCancel) {
        g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
        return false;
    }
    if (m_bCreateISO)
    {
        //m_oCreateISO.append(root->destination());
        m_oCreateISO.append(m_odestination);
        m_oArguments << m_oCreateISO;
        m_oProcess->setArguments(m_oArguments);
        for (int i = 0; i < m_oArguments.size(); ++i)
        {
            qDebug() << QString("Arg.%1 - %2").arg(i + 1).arg(m_oArguments.at(i));
        }
        qDebug() << "";

        //cdrom->m_bStart(true);
        cloneCDROM->updateCDROMBurnStart(true);
        m_oProcess->start();
        while (m_oProcess->state() != QProcess::NotRunning){
            //qDebug()<<__func__<<__LINE__;
            QCoreApplication::processEvents();
        }
        if(!m_oKeep) return false;
        m_bCreateISO = false;
    }
    if (m_bCancel) {
        qDebug()<<__func__<<__LINE__<<m_bCancel;
        g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
        return false;
    }
    m_oArguments.clear();
    m_oArguments << "-c";
    if (cloneCDROM->mediumType().startsWith("CD"))
    {
        if (m_bAppendBurn)
        {
            cloneCDROM->umount();
            m_oMSINFO = QString("cdrecord -msinfo dev=%1").arg(cloneCDROM->device());
            m_oArguments << m_oMSINFO;
            m_oProcess->setArguments(m_oArguments);
            for (int i = 0; i < m_oArguments.size(); ++i)
            {
                qDebug() << QString("Arg.%1 - %2").arg(i + 1).arg(m_oArguments.at(i));
            }
            qDebug() << "";
            m_oProcess->start();
            while (m_oProcess->state() != QProcess::NotRunning)
                QCoreApplication::processEvents();
            m_bAppendBurn = false;
            m_oArguments.clear();
            m_oArguments << "-c";
            m_oMkisofs.append(QString("-C \"%1\"").arg(m_oMSINFO));
            m_oMkisofs.append(" ");
            m_oMkisofs.append(QString("-M \"%1\"").arg(cloneCDROM->device()));
            m_oMkisofs.append(" ");
        }
        //m_oMkisofs.append(root->destination());
        qDebug()<<__func__<<__LINE__<<m_odestination;
        m_oMkisofs.append(m_odestination);
        m_oMkisofs.append(" ");
        m_oCdrecord.append(QString("dev=%1 -").arg(cloneCDROM->device()));
        m_oArguments << QString("%1 | %2").arg(m_oMkisofs).arg(m_oCdrecord);
    }
    else if (cloneCDROM->mediumType().contains("DVD+R DL"))
    {
        if (!cloneCDROM->settingCloseSession())
            //  m_oXorriso = QString("xorriso -dev %1 -map \"%2\" \"%3\" -volid \"%4\" -close off -commit -eject").arg(cloneCDROM->device()).arg(root->destination()).arg("/").arg(cloneCDROM->settingVolumnID());
            m_oXorriso = QString("xorriso -dev %1 -map \"%2\" \"%3\" -volid \"%4\" -close off -commit -eject").arg(cloneCDROM->device()).arg(m_odestination).arg("/").arg(cloneCDROM->settingVolumnID());
        else
            //  m_oXorriso = QString("xorriso -dev %1 -map \"%2\" \"%3\" -volid \"%4\" -close on -commit -eject").arg(cloneCDROM->device()).arg(root->destination()).arg("/").arg(cloneCDROM->settingVolumnID());
            m_oXorriso = QString("xorriso -dev %1 -map \"%2\" \"%3\" -volid \"%4\" -close on -commit -eject").arg(cloneCDROM->device()).arg(m_odestination).arg("/").arg(cloneCDROM->settingVolumnID());

        //qDebug() << "m_oXorriso = " << m_oXorriso;
        info(_("the command for xorriso is: %1").arg(m_oXorriso));
        cloneCDROM->umount(); //xorriso刻录需要先卸载光盘
        m_oArguments << m_oXorriso;
    }
    else
    {
        if (m_bAppendBurn){
            qDebug()<<"root->destination()"<<m_odestination;
            // m_oGrowisofs.append(QString("-M %1 \"%2\"").arg(cloneCDROM->device()).arg(root->destination()));
            m_oGrowisofs.append(QString("-M %1 \"%2\"").arg(cloneCDROM->device()).arg(m_odestination));

            qDebug()<<"root->destination()"<<m_odestination;
        }else{
            // m_oGrowisofs.append(QString("-Z %1 \"%2\"").arg(cloneCDROM->device()).arg(root->destination()));
            qDebug()<<__func__<<__LINE__<<cloneCDROM->device()<<m_odestination;
            m_oGrowisofs.append(QString("-Z %1 \"%2\"").arg(cloneCDROM->device()).arg(m_odestination));
        }
        m_oArguments << m_oGrowisofs;
    }
    m_oProcess->setArguments(m_oArguments);
    info(_("Argument setted for %1:").arg(m_oProcess->program()));
    for (int i = 0; i < m_oArguments.size(); ++i)
    {
        debug(_("Arg.%1 - %2").arg(i + 1).arg(m_oArguments.at(i)));
    }

    for (int i = 0; i < m_oArguments.size(); ++i)
    {
        qDebug() << QString("Arg.%1 - %2").arg(i + 1).arg(m_oArguments.at(i));
    }
    qDebug() << "";

    m_oProcess->start();
    while (m_oProcess->state() != QProcess::NotRunning)
        QCoreApplication::processEvents();
    return m_oKeep;
}

bool ProcessBurnData::worked()
{
    if (m_bCancel) return false;
    if (QProcess::NormalExit != m_oProcess->exitStatus()) return false;
    return m_oKeep;
}

void ProcessBurnData::slotsStart()
{
    cancel(false);
}

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

    output = m_oProcess->readAllStandardOutput();
    //qDebug() << "slotsOutput = " << output;
    if (m_bCancel)
        m_oProcess->kill();
    if (m_bAppendBurn)
    {
        m_oMSINFO.clear();
        m_oMSINFO = output.trimmed();
    }

    //CD光盘命令刻录数据返回的打印信息
    basic = 99 - m_iProgress;

    if (output.contains("Performing OPC"))
    {
        setValue(++m_iProgress, m_oIcon, _("Performing OPC"));
        cancel(false);
    }
    if (output.startsWith("\rTrack"))
    {
        // 例子：Track 01:   57 MB written (fifo 100%) [buf 100%]  10.2x.
        // CD盘进度条有问题：不能计算刻录进度，只有已刻录容量没有总容量
        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();
        //qDebug() << "slotsOut si = " <<si << "   s.at(2)" << s.at(2);

        t = s.at(4).toDouble();
        if (t==0) t = m_oNewSize;
        //qDebug() << "slotsOut t = " <<t<< "   s.at(4)" << s.at(4);
        if (s.size() > 5)
        {
            tmp = m_iProgress + (si / t * basic);
            if(tmp >= 99) tmp = 99;
            setValue(tmp, 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)"));
    info(output);
}

void ProcessBurnData::slotsError()
{
    qreal v;
    qreal tmp;
    int basic;
    QString output;
    QStringList ss;
    DataCDROM *cdrom;
    cdrom = (DataCDROM *)m_oCDROM;
    output = m_oProcess->readAllStandardError();
    //qDebug() << "slotsError = " << output;
    if (output.contains("OPC failed."))
        m_oKeep = false;
    if (output.contains("Input/output error")) {
        m_oKeep = false;
        m_lastErrorMsg = QString(_("Input/output error. Disc may be damaged, please clean or replace a disc and try again."));
    }
    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;
    if (output.contains(":-(")) {
        info(QString("[%1] [%2] 发现错误： [%3]").arg(__func__).arg(__LINE__).arg(output));
        if (m_oFlag && output.contains(":-( unable to reload tray")){
            m_oKeep = true;
            info(QString("[%1] [%2] 出现 :-( unable to reload tray, 不认为是错误输出 设置m_oKeep = [%3]").arg(__func__).arg(__LINE__).arg(m_oKeep));
        } else {
            m_oKeep = false;
        }
    }

    if (output.contains("xorriso : aborting"))
        m_oKeep = false;
    if(output.contains("seems to be mounted!")) // CD盘光盘不能卸载
        m_oKeep = false;
    if(output.contains("target is busy")) // CD盘光盘不能卸载
        m_oKeep = false;
    if(output.contains("Cannot open busy device")) //xorriso卸载失败
        m_oKeep = false;
    if(output.contains("No such device")) {
        /** CD盘刻录镜像时，光驱拔出后报错，进程需等待10分钟结束，不会立即结束，用户感知刻录镜像
         * 失败后不弹框，所以直接杀死进程
         **/
        if (m_oProcess->state() != QProcess::NotRunning)
        {
            m_oKeep = false;
            debug(_("An error occurs when the CD is removed during data burning. The image burning process is terminated."));
            m_oProcess->kill();
        }
    }

    if(cloneCDROM->mediumType().contains("DVD+R DL"))
    {
        basic = 90 - m_iProgress;
        //提取命令返回值的刻录进度值
        if(output.startsWith("xorriso : UPDATE : Writing"))
        {
            ss = output.split(" ");
            for(int i = 0; i < ss.size(); ++i)
            {
                //qDebug() << "slotError  ss.at(i) = " << ss.at(i);
                if(ss.at(i).contains("%"))
                {
                    //qDebug() << "slotError  ss.at(i) = " << ss.at(i) << "%";
                    v = ss.at(i).left(ss.at(i).indexOf("%")).toDouble();
                    //qDebug() << "slotError  v = " << v;
                    //qDebug() << "slotError  m_iProgress = " << m_iProgress;
                    tmp = m_iProgress + (v / 100.0 * basic);
                    if (tmp >= 90) tmp = 90;
                    setValue(tmp, m_oIcon, _("DVD+R DL medium is burning..."));
                    break;
                }
            }
        }
        else if(output.contains("xorriso : UPDATE : Closing track/session")) //DVD+R DL在Closing track/session需要一点时间，使用1s的定时器做一个假的进度条
        {
            if(!m_oProgressBarTimer_DVD->isActive())
            {
                //qDebug() << "m_oProgressBarTimer_DVD不是忙的";
                m_iProgress = 90;
                m_oProgressBarTimer_DVD->start(1000);
            }
            else
            {
                //qDebug() << "m_oProgressBarTimer_DVD是忙的";
            }
        }
        else if(output.contains("completed successfully"))
        {
            m_oProgressBarTimer_DVD->stop();
            disconnect(m_oProgressBarTimer_DVD, SIGNAL(timeout()), this, SLOT(slotsProcessBarDVD()));
            setValue(100, m_oIcon, _("completed successfully."));
        }
    }
    else  //除DVD-R DL盘后的其它DVD盘
    { 
        if (m_bCreateISO) basic = 60 - m_iProgress;
        else basic = 99 - m_iProgress;

        if (output.contains("done, estimate"))
        {
            //例子：  8.96% done, estimate finish Wed Mar  2 15:10:17 2022\n
            output = output.left(output.indexOf('%'));
            v = output.toDouble();
            //qDebug() << "slotsError DVD v = " << v;
            v = (v / 100.00) * basic;
            tmp = v + m_iProgress;
            //qDebug() << "slotsError DVD tmp = " << tmp;
            if (tmp > 99) tmp = 99;
            if (m_bCreateISO)
                setValue(tmp, m_oIcon, _("Building ISO %1").arg(m_oISOOutput));
            else
            {
                if (m_fSpeed > 0)
                    setValue(tmp, 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"));
        }

        if(output.contains("reloading tray") /*&& cdrom->getVendor().contains("ATAPI")*/){
            m_oFlag = true;
            info(QString("[%1] [%2]  run return value: reloading tray 设置m_oFlag = [%3]").arg(__func__).arg(__LINE__).arg(m_oFlag));
        }
    }

    error(output);
}

void ProcessBurnData::slotsFinished(int code, QProcess::ExitStatus status)
{
    DataCDROM *cdrom;

    cdrom = (DataCDROM *)m_oCDROM;

    info(_("Exit code is %1, status : %2, m_oKeep : %3").arg(code).arg(status).arg(m_oKeep));
    if (m_bAppendBurn && cloneCDROM->mediumType().contains("CD")) return;
    g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
    if (!m_bCreateISO) setValue(99, m_oIcon, _("Burn Data"));
    if (QProcess::NormalExit == status && 0 == code)
    {
        qDebug()<<__func__<<__LINE__<<m_bCreateISO;
        if(m_bCreateISO)
        {
            //点击“创建镜像”
            info( QString("file:[%1] line:[%2] : slotsFinished() create ISO success.").arg(__FILE__).arg(__LINE__) );
            return;
        } else {
            info(QString("file:[%1] line:[%2]: slotsFinished() burner data success.").arg(__FILE__).arg(__LINE__) );
        }
    }
    else
    {
        if(m_bCreateISO)
        {
            //点击“创建镜像”
            info( QString("file:[%1] line:[%2] : slotsFinished() create ISO failed.").arg(__FILE__).arg(__LINE__) );
            error( QString("file:[%1] line:[%2] : slotsFinished() create failure. [%3]").arg(__FILE__).arg(__LINE__).arg(m_oProcess->errorString()) );
            m_oCreateIsoLog.ouputCreateResult(cloneCDROM->display(), cloneCDROM->mDisplay(), true==m_oKeep);
            m_oKeep = false;
            return;
        } else {
            error( QString("file:[%1] line:[%2] : slotsFinished() Medium burn data failure. [%3]").arg(__FILE__).arg(__LINE__).arg(m_oProcess->errorString()) );
        }
        qDebug()<<__func__<<__LINE__<<m_bCreateISO;
        if (m_oFlag && m_oKeep && (1 == code)){
            qDebug() << __LINE__ << __func__ << "出现 :-( unable to reload tray, 不认为是错误输出 m_oFlag = " << m_oFlag << " m_oKeep = " << m_oKeep << "code = " << code;
            m_oKeep = true;
        } else {
            m_oKeep = false;
        }
        error( QString("file:[%1] line:[%2] : slotsFinished() Medium burn data failure. [%3]").arg(__FILE__).arg(__LINE__).arg(m_oProcess->errorString()) );

    }
    qDebug()<<__func__<<__LINE__<<status;

    //cdrom->m_bStart(false);
    cloneCDROM->updateCDROMBurnStart(false);
    emit g_user_signal->noMedium(cdrom);
    cloneCDROM->eject();

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

void ProcessBurnData::slotsCopy(QString src, QString des)
{
    qreal v;
    int basic;
    //DataDirectory *root;

    //root = (DataDirectory *)(m_oRoot);
    if(m_isSpecialMachine==true){
        auditburner->set("burner-os-auditlog-name",auditlogpath);
        m_oBurnDataLog.appendFile(src);                         //待刻录的源文件
    }else{
        auditburner->set("burner-os-auditlog-name","");
    }

    if (m_bCreateISO) basic = 30 - m_iProgress;
    else basic = 50 - m_iProgress;
    ++m_iCopied;
    //v = ((m_iCopied * 1.0) / (root->total() * 1.0));
    v = ((m_iCopied * 1.0) / (m_ototal * 1.0));
    v = v * basic;
    m_iProgress += v;
    setValue(m_iProgress, m_oIcon, _("Copied %1 to %2").arg(src).arg(des));
    debug(_("Copied %1 to %2").arg(src).arg(des));
}


void ProcessBurnData::slotsProcessBarDVD()
{

    m_iProgress += 1;
    if (m_iProgress > 99) m_iProgress = 99;
    setValue(m_iProgress, m_oIcon, _("closing track"));
}

void ProcessBurnData::slotsRemoveDisc(QString dev)
{
    if(dev == cloneCDROM->device()) {
        if(m_oProcess->state() != QProcess::NotRunning) {
            qDebug() << __func__ << __LINE__ << dev << "被拔出，杀死刻录数据进程";
            info(QString("[%1] [%2] : %3 被拔出，杀死刻录数据进程").arg(__func__).arg(__LINE__).arg(dev));
            m_oProcess->kill();
        }
    }
}


ProcessBurnData::~ProcessBurnData()
{
    if(m_oProgressBarTimer_DVD!=nullptr)
        delete m_oProgressBarTimer_DVD;
    m_oProgressBarTimer_DVD = nullptr;
    //info(QString("[%1] [%2] : 将要delete cloneCDROM").arg(__func__).arg(__LINE__));
    if(cloneCDROM) {
        delete cloneCDROM;
        //info(QString("[%1] [%2] : 执行delete cloneCDROM").arg(__func__).arg(__LINE__));
    }
    cloneCDROM = nullptr;
}
