#include "smanage.h"
#include "widget.h"

SManage::SManage(QObject *parent) :
    QObject(parent),m_pMain(0)
{
    for(int i = 0; i < C_PROCESS_MAX ;i++)
        connect(&m_pro[i],SIGNAL(finished(int,QProcess::ExitStatus)),SLOT(processFinished(int,QProcess::ExitStatus)));
}

void SManage::Start(QDate _StartDate,QDate _EndDate,QString _strKeyword,QString _strAuthorship,QString _strKeywordID,QString _strGroupID,int _nStart,int _nTime)
{
    m_date = _StartDate;
    m_dateEnd = _EndDate;
    m_strKeyword = _strKeyword;
    m_bFinalLast = false;
    m_nTime = _nTime;
    m_strKeywordID = _strKeywordID;
    m_strAuthorship = _strAuthorship;
    m_ncList = _nStart;
    m_strGroupID = _strGroupID;
    Start();
}

void SManage::SetParent(Widget *_pWidget)
{
    m_pMain = _pWidget;
}

QString SManage::EncodetoUtf8(QString _str,bool _bExt)
{
    QString strOut;
    for (int i = 0; i < _str.length(); i++)
    {
        QString strTran = _str.at(i);
        QByteArray byte = strTran.toUtf8();
        if (byte.length() == 3)
        {
            QByteArray byteHan = byte.toHex().toUpper();
            for (int j = 0; j < 3 ; j++)
            {
                strOut += "%";
                for (int k = 0; k < 2; k++)
                    strOut += byteHan.at(j*2+k);
            }
        }
        else if (_str.at(i).isDigit() || _str.at(i).isLower() || _str.at(i).isUpper())
            strOut += _str.at(i);
        else if (_bExt && _str.at(i) == '@' || _str.at(i) == '*' || _str.at(i) == '_' || _str.at(i) == '.')
            strOut += _str.at(i);
        else if (_bExt && _str.at(i) == ' ')
            strOut += '+';
        else
        {
            strOut += "%";
            strOut += byte.toHex().toUpper();
        }
    }
    return strOut;
}

bool SManage::UseProcess()
{
    for(int i = 0; i < C_PROCESS_MAX ; i++)
    {
        if (m_pro[i].state() == QProcess::Running)
            return true;
    }
    return false;
}

void SManage::processFinished(int exitCode,QProcess::ExitStatus exitStatus)
{
    SProcess *pPro = (SProcess*)sender();
    QString str = pPro->readAllStandardOutput();
    QStringList list = str.split("\n");
    foreach(QString log,list)
    {
        if (m_pMain)
            m_pMain->InsertLog(m_nID,log);
        else
            exit(0);
    }
    pPro->SetState(SProcess::STATE_WAIT);
    processFinished(pPro,str);
    pPro->kill();
}

void SManage::CheckLast()
{
    if (m_bLast)
    {
        m_date = m_date.addDays(1);
        if (m_date > m_dateEnd)
        {
            m_bFinalLast = true;
        }
        m_ncList=1;
    }
}

void SManage::WaitExitProcess()
{
    bool bQuit = true;
    while(bQuit)
    {
        for(int i = 0; i < C_PROCESS_MAX ; i++)
        {
            if (m_pro[i].State() != SProcess::STATE_WAIT)
                m_pro[i].kill();
        }
        bQuit = UseProcess();
    }
}

