#include "processmediainfo.h"
#include "src/view/modaldialog.h"
#include "src/data/datacdrom.h"
#include "src/po/translation.h"
#include <QDebug>
#include <QFileInfo>

ProcessMediaInfo::ProcessMediaInfo(void *d, QObject *parent) :
    ProcessBasic(parent),
    m_oCDROM(d),
    m_u64Size(0)
{
	m_oProcessName = _("Media Info");
    cloneCDROM = ((DataCDROM *)d)->clone();
}

bool ProcessMediaInfo::prepare()
{
    if (!MODAL->isHidden()) MODAL->close();
    disconnect(this, SIGNAL(success(QString)), TIP, SIGNAL(success(QString)));
    disconnect(this, SIGNAL(fail(QString)), TIP, SIGNAL(fail(QString)));

    m_oProcess->setProgram("dvd+rw-mediainfo");
    m_oArguments << cloneCDROM->device();
    m_oProcess->setArguments(m_oArguments);
    return true;
}

void ProcessMediaInfo::slotsError()
{
    QString error;

    error = m_oProcess->readAllStandardError();
}

void ProcessMediaInfo::slotsOutput()
{
    int     i;
    unsigned long t;
    unsigned long u;
    QString output;
    QStringList ss;
    QStringList sss;

    if (m_u64Size) return;

    output = m_oProcess->readAllStandardOutput();
    ss = output.split("\n");
    for (i = ss.size() - 1; i > 0; --i)
    {
        if (ss.at(i).startsWith("READ FORMAT CAPACITIES:")) break;
    }

    if (cloneCDROM->mediumType().contains("DVD+RW"))
    {
        ss = ss.takeAt(i + 1).split("=");
        //ss = ss.last().split("=");
        m_u64Size = ss.last().toULong();
    }
    if (cloneCDROM->mediumType().contains("DVD-RW"))
    {
        //解决bug:70940和83628擦除后总容量显示错误
#if 0
        sss = ss.takeAt(i + 1).split("=");
        t = 0;
        u = 0;
        u = sss.last().toULong();//unformatted的容量
        sss = ss.takeAt(i + 2).split("=");
        t = sss.last().toULong();//00h(800h)的容量
        if (t > u) m_u64Size = t - u;
        else m_u64Size = u;
        //出现下面这种情况导致bug出现
        //no media:		4101552*2048=8399978496
        //00h(800):		2297888*2048=4706074624
#else
        sss = ss.takeAt(i + 2).split("=");
        t = sss.last().toULong();
        m_u64Size = t;
#endif
    }
}

ProcessMediaInfo::~ProcessMediaInfo()
{
    qDebug() << __func__ << __LINE__  << "----------------";
#if 0
    if(m_oProcess!=nullptr)
    {
        delete m_oProcess;
        m_oProcess = nullptr;
    }
#else

    m_oProcess->close();
#endif
}
