#include "widget.h"
#include "ui_widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QDebug>
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QSize>
#include <QRegExp>
#include <QWebPage>
#include <QWebElement>
#include <QWebFrame>


void SleepThread::run()
{
    QThread::sleep(1);
}


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget), m_bUsed(false)
{
    ui->setupUi(this);
    QVBoxLayout *vlayout = new QVBoxLayout();
    initTable();
    vlayout->addWidget(m_pTable);
    vlayout->addLayout(initInputLayout());
    vlayout->addLayout(initButtonLayout());
    setWindowTitle("NaverCafeListManager");
    resize(600, 400);
    setLayout(vlayout);
    initWebPage();
    initDatabase();
    pushRefresh();
}

QHBoxLayout* Widget::initButtonLayout()
{
    QHBoxLayout *hlayout = new QHBoxLayout();

    m_pbtnAdd = new QPushButton("Add");
    m_pbtnDel = new QPushButton("Del");
    m_pbtnModify = new QPushButton("Modify");
    m_pbtnRefresh = new QPushButton("Refresh");
    m_pbtnGetClubid = new QPushButton("GetClubID");

    connect(m_pbtnAdd, SIGNAL(clicked()), this, SLOT(pushAdd()));
    connect(m_pbtnDel, SIGNAL(clicked()), this, SLOT(pushDel()));
    connect(m_pbtnModify, SIGNAL(clicked()), this, SLOT(pushModify()));
    connect(m_pbtnRefresh, SIGNAL(clicked()), this, SLOT(pushRefresh()));
    connect(m_pbtnGetClubid, SIGNAL(clicked()), this, SLOT(pushGetClubId()));

    hlayout->addWidget(m_pbtnAdd);
    hlayout->addWidget(m_pbtnDel);
    hlayout->addWidget(m_pbtnModify);
    hlayout->addWidget(m_pbtnRefresh);
    hlayout->addWidget(m_pbtnGetClubid);

    return hlayout;
}

QHBoxLayout* Widget::initInputLayout()
{
    QHBoxLayout *hlayout = new QHBoxLayout();

    m_pleUrl = new QLineEdit;
    m_pleGroup = new QLineEdit;
    m_pleClubId = new QLineEdit;

    hlayout->addWidget(new QLabel("Url:"));
    hlayout->addWidget(m_pleUrl, 3);
    hlayout->addWidget(new QLabel("Group:"));
    hlayout->addWidget(m_pleGroup, 1);

    hlayout->addWidget(new QLabel("Club ID:"));
    hlayout->addWidget(m_pleClubId, 2);
    return hlayout;
}


void Widget::initTable()
{
    m_pTable = new STable;
    m_pQueryTable = new QSqlQueryModel;
    m_pTable->setModel(m_pQueryTable);

    m_pTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_pTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_pTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    m_pTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    //connect(m_pTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(clickTable(QModelIndex, QModelIndex)));
    connect(m_pTable, SIGNAL(clicked(QModelIndex)), this, SLOT(clickTable(QModelIndex)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::pushAdd()
{
    if(!checkUrl() || !checkGroup())
    {
        return;
    }
    QString strquery;

    if(isClubIdNull())
    {
        strquery = "insert into navercafelist (url, group_num) values (";
        strquery += ("'" + m_pleUrl->text().trimmed() + "',");
        strquery += m_pleGroup->text().trimmed() + ")";
    }
    else
    {
        if(checkClubId())
        {
            strquery = "insert into navercafelist (url, group_num, clubid) values (";
            strquery += ("'" + m_pleUrl->text().trimmed() + "',");
            strquery += m_pleGroup->text().trimmed() + ",";
            strquery += m_pleClubId->text().trimmed() + ")";
        }
        else
        {
            return;
        }
    }

    QSqlQuery query;
    if(!query.exec(strquery))
    {
        showMessage(query.lastError().text() + "\n\n" + "Check url, group and clubid");
        return;
    }
    pushRefresh();
}

void Widget::pushDel()
{
    QStringList ids = selectedIds();
    QString strquery = "delete from navercafelist where id = ";
    QSqlQuery query;
    foreach(QString id, ids)
    {
        if(!query.exec(QString(strquery + id)))
        {
            showMessage(query.lastError().text() + "\n\nError occurs");
            return;
        }
    }

    pushRefresh();
}

void Widget::pushModify()
{
    if(!checkUrl() || !checkGroup())
    {
        return;
    }
    QStringList ids = selectedIds();

    QString strquery = "update navercafelist set url = '";
    strquery += m_pleUrl->text().trimmed() + "', group_num = ";
    strquery += m_pleGroup->text().trimmed();
    if(!isClubIdNull())
    {
        if(checkClubId())
        {
            strquery += ", clubid = " + m_pleClubId->text().trimmed();
        }
        else
        {
            return;
        }
    }
    strquery += " where id = ";
    QSqlQuery query;
    foreach(QString id, ids)
    {
        if(!query.exec(strquery + id.trimmed()))
        {
            showMessage(query.lastError().text() + "\n\nError occurs.\nCheck url and group");
            return;
        }
    }

    pushRefresh();
}

void Widget::pushRefresh()
{
    if(!connectDatabase())
    {
        return;
    }
    m_pQueryTable->setQuery("select id, url, group_num, clubid from navercafelist");
}

void Widget::clickTable(const QModelIndex &index)
{
    m_pleUrl->setText(m_pQueryTable->record(index.row()).value(E_COLUMN_URL).toString().trimmed());
    m_pleGroup->setText(m_pQueryTable->record(index.row()).value(E_COLUMN_GROUP).toString().trimmed());
    m_pleClubId->setText((m_pQueryTable->record(index.row()).value(E_COLUMN_CLUBID).toInt() < 1)? "" : (m_pQueryTable->record(index.row()).value(E_COLUMN_CLUBID).toString().trimmed()));
}


bool Widget::initDatabase()
{
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName("bigbird.iptime.org");
    m_db.setUserName("admin");
    m_db.setPassword("admin123");
    m_db.setDatabaseName("concepters");
    return connectDatabase();
}

bool Widget::connectDatabase()
{
    if(!m_db.isOpen() && !m_db.open())
    {
        showMessage("DB Error");
        return false;
    }
    return true;
}

void Widget::showMessage(QString strMessage)
{
    QMessageBox msg;
    msg.setIcon(QMessageBox::Critical);
    msg.setText(strMessage);
    msg.exec();
}

bool Widget::checkGroup()
{
    bool ok;
    m_pleGroup->text().trimmed().toInt(&ok);
    if(!ok)
    {
        showMessage("Put Number in the group field, Insert Error");
        return false;
    }
    return true;
}

bool Widget::checkUrl()
{
    QRegExp rx("^http://cafe.naver.com/.+");
    if(rx.indexIn(m_pleUrl->text().trimmed()) < 0)
    {
        showMessage("Check url form \nhttp://cafe.naver.com/xxxxxxxx");
        return false;
    }
    return true;
}

QStringList Widget::selectedIds()
{
    QStringList ids;
    foreach(QModelIndex index, m_pTable->selectionModel()->selectedRows(E_COLUMN_ID))
    {
        ids.append(index.data(Qt::DisplayRole).toString().trimmed());
    }
    ids.removeDuplicates();
    return ids;
}

bool Widget::isClubIdNull()
{
    if(m_pleClubId->text().trimmed().length() < 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void Widget::pushGetClubId()
{
    QSet<QString> urls;
    foreach(QModelIndex index, m_pTable->selectionModel()->selectedRows(E_COLUMN_URL))
    {
        urls.insert(index.data(Qt::DisplayRole).toString().trimmed());
    }

    for(QSet<QString>::iterator iterPos = urls.begin(); iterPos != urls.end(); iterPos++)
    {
        loadUrl(QString(*iterPos));
    }
}

bool Widget::checkClubId()
{
    QRegExp rx("^[\\d]+$");
    if(rx.indexIn(m_pleClubId->text().trimmed()) < 0)
    {
        showMessage("Check ClubId\nClubid is consist of Only Numbers");
        return false;
    }
    return true;
}

void Widget::loadUrl(QString url)
{
    while(m_bUsed)
    {
        m_thread.run();
        m_thread.wait();
    }
    m_bUsed = true;
    m_pPage->settings()->clearMemoryCaches();
    m_pPage->mainFrame()->load(QUrl(url));
}

void Widget::initWebPage()
{
    m_pPage = new QWebPage;
    m_pPage->settings()->setAttribute(QWebSettings::AutoLoadImages,false);

    connect(m_pPage, SIGNAL(loadFinished(bool)), this, SLOT(readWebPage(bool)));
}

void Widget::readWebPage(bool ok)
{
    if(!ok)
    {
        showMessage("Load Url Failed");
        m_bUsed = false;
        return;
    }

    QWebElementCollection as = m_pPage->mainFrame()->findAllElements("a");
    QString href;
    foreach(QWebElement a, as)
    {
        if(a.attribute("name").compare("myCafeUrlLink", Qt::CaseInsensitive) == 0)
        {
            href = a.attribute("href");
            break;
        }
    }

    QRegExp rx("clubid=([\\d]+)");
    int pos = 0;
    while((pos = rx.indexIn(href, pos)) != -1)
    {
        //updateAllClubId(m_pPage->mainFrame()->baseUrl().toString(), rx.cap(1));
        m_pleClubId->setText(rx.cap(1));
        pos += rx.matchedLength();
    }
    m_bUsed = false;
}

void Widget::updateAllClubId(QString url, QString clubid)
{
    QString strquery = "update navercrawler set clubid = " + clubid.trimmed() + " where url = " + url.trimmed();
    QSqlQuery query;
    if(!query.exec(strquery))
    {
        showMessage(query.lastError().text() + "\n\n" + query.lastQuery());
    }
}
