#include "widget.h"
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QHBoxLayout>
#include <QTime>
#include <QProcess>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{    
    m_pbtDelete = new QPushButton ("Delete",this);
    QObject::connect(m_pbtDelete,SIGNAL(clicked()),this,SLOT(DeleteButton()));
    m_pbtMake = new QPushButton ("Make",this);
    QObject::connect(m_pbtMake,SIGNAL(clicked()),this,SLOT(MakeButton()));
    m_pbtSend = new QPushButton ("Send",this);
    QObject::connect(m_pbtSend,SIGNAL(clicked()),this,SLOT(SendButton()));

    QVBoxLayout *vlayout = new QVBoxLayout;
    {
        QHBoxLayout *hlayout = new QHBoxLayout;
        hlayout->addWidget(m_pbtDelete);
        hlayout->addWidget(m_pbtMake);
        hlayout->addWidget(m_pbtSend);
        vlayout->addLayout(hlayout);
    }
    vlayout->addWidget(&m_listResult);
    setLayout(vlayout);
}

Widget::~Widget()
{
    delete m_pbtDelete;
    delete m_pbtMake;
    delete m_pbtSend;
}

void Widget::DeleteButton()
{
    QSqlDatabase dbData = QSqlDatabase::addDatabase("QMYSQL");
    dbData.setUserName("root");
    dbData.setDatabaseName("concepters");

    if (!dbData.open())
    {
        qDebug() << dbData.lastError().text();
    }

    InsertLog("Delete Start");
    QSqlQuery sql = dbData.exec("Delete from THIRD_ARTICLE_LIST");
    if (sql.lastError().isValid())
        InsertLog(sql.lastError().text());
    else
        InsertLog("Delete Ok");

    dbData.close();
}

void Widget::InsertLog(QString str)
{
    QTime time = QTime::currentTime();
    QString strOut = time.toString("[hh:mm:ss] ") + str;
    m_listResult.addItem(strOut);
    if (m_listResult.count() > 1024)
    {
        m_listResult.removeItemWidget(m_listResult.item(0));
        QListWidgetItem* item = m_listResult.takeItem(0);
        delete item;
    }
    m_listResult.setCurrentRow( m_listResult.count() - 1 );
    m_listResult.repaint();
    /*
    QDate date = QDate::currentDate();
    QFile file(date.toString(Qt::ISODate)+"_"+QString::number(_nSelect)+".log");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        return;

    QTextStream out(&file);
    out << strOut << "\n";
    file.close();
    */
}


void Widget::MakeButton()
{
    QSqlDatabase dbData = QSqlDatabase::addDatabase("QMYSQL");
    dbData.setUserName("root");
    dbData.setDatabaseName("concepters");

    if (!dbData.open())
    {
        qDebug() << dbData.lastError().text();
    }
    QSqlQuery sql;
    sql = dbData.exec("insert into THIRD_ARTICLE_LIST(PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE )"
                      "select "
                      "'naver' , 'blog' , 'article',"
                      "OTHER , TITLE , URL , NICK , DATE , LEFT(DATA,8192)"
                      "from blog");
    if (sql.lastError().isValid())
    {
        InsertLog(sql.lastError().text());
        return;
    }
    InsertLog("Insert 1 OK");
    sql = dbData.exec("insert into THIRD_ARTICLE_LIST(PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE )"
                      "select "
                      "'naver' , 'cafe' , 'article',"
                      "OTHER , TITLE , URL , NICK , DATE , LEFT(DATA,8192)"
                      "from cafe");
    if (sql.lastError().isValid())
    {
        InsertLog(sql.lastError().text());
        return;
    }
    InsertLog("Insert 2 OK");    
    sql = dbData.exec("insert into THIRD_ARTICLE_LIST(PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE,ARTICLE_REPLY)"
                        "select "
                        "CONVERT('naver' USING utf8),"
                        "CONVERT('blog' USING utf8),"
                        "CONVERT('reply' USING utf8),"
                        "CONVERT(b.OTHER USING utf8),"
                        "CONVERT(b.TITLE USING utf8),"
                        "CONVERT(b.URL USING utf8),"
                        "CONVERT(c.NICK USING utf8),"                        
                        "CONVERT(c.DATE USING utf8),"
                        "CONVERT(LEFT(b.DATA,8192) USING utf8),"
                        "CONVERT(LEFT(c.DATA,8192) USING utf8)"
                        "FROM blog b inner join comment c on b.url = c.url");

    if (sql.lastError().isValid())
    {
        InsertLog(sql.lastError().text());
        qDebug() << sql.lastError().text();
        return;
    }
    InsertLog("Insert 3 OK");

    sql = dbData.exec("insert into THIRD_ARTICLE_LIST(PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE,ARTICLE_REPLY)"
                      "select "
                      "CONVERT('naver' USING utf8),"
                      "CONVERT('cafe' USING utf8),"
                      "CONVERT('reply' USING utf8),"
                      "CONVERT(ca.OTHER USING utf8),"
                      "CONVERT(ca.TITLE USING utf8),"
                      "CONVERT(ca.URL USING utf8),"
                      "CONVERT(co.NICK USING utf8),"                      
                      "CONVERT(co.DATE USING utf8),"
                      "CONVERT(LEFT(ca.DATA,8192) USING utf8),"
                      "CONVERT(LEFT(co.DATA,8192) USING utf8)"
                      "FROM cafe ca inner join cafe_comment co on ca.url = co.url");
    if (sql.lastError().isValid())
    {
        InsertLog(sql.lastError().text());
        return;
    }

    InsertLog("Insert Finish");
}

void Widget::SendButton()
{    
    QSqlDatabase dbData = QSqlDatabase::addDatabase("QMYSQL");
    dbData.setUserName("root");
    dbData.setDatabaseName("concepters");
    if (!dbData.open())
    {
        qDebug() << dbData.lastError().text();
    }

    InsertLog("Send Start");
    QSqlQuery sql = dbData.exec("select PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE,ARTICLE_REPLY from THIRD_ARTICLE_LIST");
    if (sql.lastError().isValid())
    {
        InsertLog(sql.lastError().text());
        return;
    }

    QStringList strlistQuery;
    QStringList strlistKeyword;
    strlistKeyword << "첫째" << "둘째" << "셋째" << "넷째";
    while (sql.next())
    {
        bool bFlag = true;
        QString strQuery = "insert into THIRD_ARTICLE_LIST(KEYWORD,PLATFORM,PLATFORM_TYPE,ARTICLE_TYPE,PLATFORM_TITLE,ARTICLE_TITLE,ARTICLE_URL,ARTICLE_NICKNAME,ARTICLE_DATE,ARTICLE_ARTICLE,ARTICLE_REPLY ) value (";
        strQuery += "'";
        strQuery += "초등&내신";
        strQuery += "',";
        for (int j = 0; j < 10 ; j++)
        {
            strQuery += "'";            
            QString str = sql.value(j).toString();
            if (j == 7)
            {
                str.replace("-","/");
                str.replace(".","/");
                if (str.left(5) == QString("Error").left(5))
                    bFlag = false;
            }
            str.replace("'","\'");
            str.replace("\"","\\\"");
            str.replace(",","");
            strQuery += str;
            strQuery += "',";
        }

        strQuery = strQuery.left(strQuery.size()-1) + ")";
        if (bFlag)
            strlistQuery.push_back(strQuery);
    }
    InsertLog("Make Query End");
    dbData.close();

    QSqlDatabase dbWeb = QSqlDatabase::addDatabase("QMYSQL");
    dbWeb.setHostName("db.big-bird.co.kr");
    dbWeb.setUserName("concepters");
    dbWeb.setPassword("con97996655");
    dbWeb.setDatabaseName("dbconcepters");
    if (!dbWeb.open())
    {
        InsertLog(dbWeb.lastError().text());
        return;
    }    
    dbWeb.exec("Delete from THIRD_ARTICLE_LIST");
    if (dbWeb.lastError().isValid())
    {
        InsertLog(dbWeb.lastError().text());
        return;
    }

    foreach(QString str,strlistQuery)
    {
        dbWeb.exec(str);
        if (dbWeb.lastError().isValid())
        {
            InsertLog(dbWeb.lastError().text());
        }
    }
    dbWeb.close();    
    InsertLog("Send End");
}
