#include "processgetiso.h"
#include "src/frame/logger.h"
#include "src/po/translation.h"
#include "src/data/datacdrom.h"
#include "src/view/modaldialog.h"
#include "src/view/execdialog.h"
#include "src/frame/signals.h"
#include "src/frame/auditlog.h"
#include <kysdk/kysdk-system/libkysysinfo.h>

#include <QFileInfo>
#include <QDir>

ProcessGetISO::ProcessGetISO(void *src, void *des, QObject *parent) :
    ProcessBasic(parent),
    m_oSource(src),
    m_oDestination(des),
    m_iProgress(0)
{
    LOGGER->registerName(this, _("PROCESS_GI"));
    m_oProcessName = _("Get ISO");
    title(_("Getting ISO"));
    setRange(0, 100);
    setValue(0);
}

bool ProcessGetISO::prepare()
{
    DataCDROM *src;
    DataCDROM *des;
    QString output;
    QFileInfo f;

    connect(this, SIGNAL(cancel(bool)), MODAL, SLOT(cancelEnable(bool)));

    f.setFile("/bin/mkisofs");
    if (!f.exists())
    {
        error(_("Cannot find program <%1>.").arg(f.fileName()));
        setValue(1, QIcon::fromTheme("dialog-error-symbolic"),
                 _("Cannot find program <%1>.").arg(f.fileName()));
        return false;
    }
    if (!f.isExecutable())
    {
        error(_("Program %1 is not executable file.").arg(f.fileName()));
        setValue(1, QIcon::fromTheme("dialog-error-symbolic"),
                 _("Program %1 is not executable file.").arg(f.fileName()));
        return false;
    }
    output.clear();
    m_oProcess->setProgram(f.fileName());
    setValue(++m_iProgress, m_oIcon, _("Preparing get iso file."));

    des = static_cast<DataCDROM *>(m_oDestination);
    f.setFile(des->device());
    output = f.absolutePath();
    output.append("/");
    src = static_cast<DataCDROM *>(m_oSource);
    if (src->mediumMountPoint().isEmpty())
    {
        error(_("Medium in CDROM %1 donot been mounted.").arg(src->display()));
        return false;
    }
    output.append(src->settingVolumnID());
    output.append(".iso");
    f.setFile(output);
    if (f.exists())
    {
        if (!EXEC->question(_("Get ISO") + " - " + _("Already Exists"),
                           _("There is already have the iso file named %1,"
                             "replace it or not?").arg(f.fileName())))
        {
            return false;
        }
        if (f.isFile()) QFile::remove(f.absoluteFilePath());
        else { QDir dir(f.absoluteFilePath()); dir.removeRecursively(); }
        debug(_("File %1 exists.").arg(f.absoluteFilePath()));
    }
    PROGRESS;
    MODAL->show();
    m_oDeviceBlock = src->device();
    g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,true);

    m_oArguments << "-o" << f.absoluteFilePath();

    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()));
    m_oArguments << src->mediumMountPoint();
    return true;
}

void ProcessGetISO::slotsError()
{
    QString output;
    qreal basic;
    int v;

    v = 0;
    basic = 99 - m_iProgress;

    output = m_oProcess->readAllStandardError();
    if (output.contains("Input/output error")) {
        m_oKeep = false;
        m_lastErrorMsg = QString(_("Bad sector detected, please clean or replace a disc and try again."));
    }
    if (output.contains("done, estimate")) // 2.50% done, estimate finish Tue Feb  2 17:15:15 2021
    {
        output = output.left(output.indexOf('%'));
        // 100 - 55 - 1 = 44
        v = output.toDouble();
        v = (v / 100.00) * basic;
        setValue(v, m_oIcon, _("Getting ISO"));
    }
    error(output);
}

void ProcessGetISO::slotsFinished(int errorCode, QProcess::ExitStatus status)
{
    AuditLog getIsoLog;
    bool m_isSpecialMachine;
    auditburner=new QGSettings("org.ukui.kylinburner");
    auditlogpath="/var/log/kylin-burner/os_audit.log";
    m_isSpecialMachine=auditburner->get("burneraudit-isrunning").toBool();
    //  m_isSpecialMachine=kdk_system_is_zyj();
    DataCDROM *src = (DataCDROM*)m_oSource;
    DataCDROM *dest = (DataCDROM*)m_oDestination;
    if(m_isSpecialMachine==true){
        auditburner->set("burner-os-auditlog-name",auditlogpath);
    getIsoLog.outputCopyResult(src->mediumMountPoint(), dest->display(), dest->mediumType(), m_oProcessName, true==m_oKeep);
    }else{
        auditburner->set("burner-os-auditlog-name","");
    }
    g_user_signal->setDeviceBusyStatus(m_oDeviceBlock,false);
    info(_("Exit code is %1, status : %2").arg(errorCode).arg(status));
    if (QProcess::NormalExit == status && 0 == errorCode)
    {
        info( QString("slotsFinished() line[%1] : get ISO success.").arg(__LINE__) );
    }
    else
    {
        m_oKeep = false;
        error( QString("slotsFinished() line[%1] : get ISO failure: %2").arg(__LINE__).arg(m_oProcess->errorString()) );
    }
}

ProcessGetISO::~ProcessGetISO()
{}
