#include "skakaotagmanage.h"
#include <QThread>
#include "widget.h"
SKakaoTagManage::SKakaoTagManage(QObject *pObject) : SManage(pObject)
{
    m_nID = 0;
    connect(&m_pro[0], SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
    connect(&m_pro[0], SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));
}


void SKakaoTagManage::Start()
{
    m_nMode = E_PROCESS_RUN;
    m_bFinalLast = false;
}

bool SKakaoTagManage::Update()
{
    if(m_bFinalLast) return m_bFinalLast;
    switch(m_nMode)
    {
    case E_PROCESS_RUN:
        if(UseProcess() == false)
        {
#if defined(Q_OS_WIN32)
            m_pro[0].start("python", QStringList() << "webbasedcrawler.py" << "kakaochannel"  << m_strKeywordID << m_strGroupID << m_pMain->StartDay() << m_pMain->UntilPage());
#else
            m_pro[0].start("/usr/bin/python3", QStringList() << "webbasedcrawler.py" << "kakaochannel"  << m_strKeywordID << m_strGroupID << m_pMain->StartDay() << m_pMain->UntilPage());
#endif
            m_nMode = E_PROCESS_FINISH_WAIT;
        }
        break;

    case E_PROCESS_FINISH_WAIT:
        break;
    }

    return m_bFinalLast;
}

void SKakaoTagManage::processFinished(QProcess *pPro, QString _strOut)
{
    switch(m_nMode)
    {
    case E_PROCESS_FINISH_WAIT:
        m_nMode = E_PROCESS_RUN;
        m_bFinalLast = true;
        m_pMain->InsertLog("Finish Crawling :)");
        m_pMain->SetCrawlingState("Finish");
        m_ncList=1;
        m_bLast = false;
        break;
    }
}

void SKakaoTagManage::readStandardOutput()
{
    QProcess *pPro = (QProcess*)sender();
    QThread::msleep(100);
    QString str = pPro->readAllStandardOutput();
    QStringList list = str.split("\n", QString::SkipEmptyParts);
    foreach(QString log,list)
    {
        if (m_pMain)
        {
            m_pMain->InsertLog(log);
        }
        else
            exit(0);
    }
}

void SKakaoTagManage::readStandardError()
{
    QProcess *pPro = (QProcess*)sender();
    QThread::msleep(100);
    QString str = pPro->readAllStandardError();
    QStringList list = str.split("\n", QString::SkipEmptyParts);
    foreach(QString log,list)
    {
        if (m_pMain)
        {
            m_pMain->InsertLog(log);
        }
        else
            exit(0);
    }
}
