#include "ymuploadwidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QSqlDatabase>
#include <QString>
#include <QSqlQuery>
#include <../Json/sjson.h>
#include "stable.h"
#include <QDebug>
#include <QSqlError>
#include "ymorpherewidget.h"
#include "stable.h"
#include "widget.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
YMUploadWidget::YMUploadWidget(QWidget *parent):QWidget(parent)
{
    m_pgbMorphere = setUploadWidgets();
    QVBoxLayout *vMainLayout = new QVBoxLayout;

    vMainLayout->addWidget(m_pgbMorphere);
    MorphereGroupRefresh();
    setLayout(vMainLayout);
}

YMUploadWidget::~YMUploadWidget()
{

}


QGroupBox *YMUploadWidget::setUploadWidgets()
{
    QHBoxLayout *hMainlayout = new QHBoxLayout();
    {
        QVBoxLayout *vlayout = new QVBoxLayout();
        m_plwMorphereGroup = new QListWidget;
        m_pleMorphereGroup = new QLineEdit;
        vlayout->addWidget(m_plwMorphereGroup);
        vlayout->addWidget(m_pleMorphereGroup);
        {
            QHBoxLayout *hlayout = new QHBoxLayout();
            QPushButton *pbInsert = new QPushButton("Insert");
            connect(pbInsert, SIGNAL(released()),this, SLOT(MorphereGroupInsert()));
            QPushButton *pbDelete = new QPushButton("Delete");
            connect(pbDelete, SIGNAL(released()),this, SLOT(MorphereGroupDelete()));
            QPushButton *pbModify = new QPushButton("Modfiy");
            connect(pbModify, SIGNAL(released()),this, SLOT(MorphereGroupModify()));
            QPushButton *pbCopy_Paste = new QPushButton("Copy&Paste");
            connect(pbCopy_Paste, SIGNAL(released()),this, SLOT(MorphereGroupCopyPaste()));
            QPushButton *pbRefresh = new QPushButton("Refresh");
            connect(pbRefresh, SIGNAL(released()),this, SLOT(MorphereGroupRefresh()));

            hlayout->addWidget(pbInsert);
            hlayout->addWidget(pbDelete);
            hlayout->addWidget(pbModify);
            hlayout->addWidget(pbCopy_Paste);
            hlayout->addWidget(pbRefresh);
            vlayout->addLayout(hlayout);
        }
        hMainlayout->addLayout(vlayout);
    }
    {
        QVBoxLayout *vlayout = new QVBoxLayout();
        m_plwMorphere = new QListWidget;
        vlayout->addWidget(m_plwMorphere);
        connect(m_plwMorphere,SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),this,SLOT(currentMorphereItemChanged(QListWidgetItem*,QListWidgetItem*)));
        QHBoxLayout *hlayout = new QHBoxLayout();
        QPushButton *pbAdd = new QPushButton("Add");
        QPushButton *pbUp = new QPushButton("Up");
        QPushButton *pbDown = new QPushButton("Down");
        QPushButton *pbDelete = new QPushButton("Delete");
        hlayout->addWidget(pbAdd);
        hlayout->addWidget(pbUp);
        hlayout->addWidget(pbDown);
        hlayout->addWidget(pbDelete);
        vlayout->addLayout(hlayout);
        connect(pbAdd, SIGNAL(released()),this, SLOT(MorphereAdd()));
        connect(pbUp, SIGNAL(released()),this, SLOT(MorphereUp()));
        connect(pbDown, SIGNAL(released()),this, SLOT(MorphereDown()));
        connect(pbDelete, SIGNAL(released()),this, SLOT(MorphereDelete()));
        hMainlayout->addLayout(vlayout);
    }
    m_pgbMorphere = new QGroupBox(tr("Upload"));
    m_pgbMorphere->setCheckable(true);
    m_pgbMorphere->setChecked(false);
    m_pgbMorphere->setLayout(hMainlayout);

    connect(m_plwMorphereGroup,SIGNAL(currentItemChanged(QListWidgetItem *,QListWidgetItem *)),this,SLOT(currentGroupItemChanged(QListWidgetItem *, QListWidgetItem *)));
    return m_pgbMorphere;
}


void YMUploadWidget::MorphereGroupInsert()
{
    /*

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");

    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    QString strQuery = QString("insert into morpheregroup set "
            "name = '" + m_pleMorphereGroup->text() + "'");
    QSqlQuery query(strQuery);

    /*
    db.exec(strQuery.toUtf8());
    db.close();
    */
    query.exec();
    MorphereGroupRefresh();
}

void YMUploadWidget::MorphereGroupDelete()
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    /*
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        QString strQuery = QString("delete from morpheregroup where id = " + item->data(Qt::UserRole).toString());
        db.exec(strQuery.toUtf8());
        strQuery = QString("delete from morphere where morpheregroup_id = " + item->data(Qt::UserRole).toString());
        db.exec(strQuery.toUtf8());
        RefreshMorphere(item->data(Qt::UserRole).toInt());
    }
    db.close();
    */
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        QString strQuery = QString("delete from morpheregroup where id = " + item->data(Qt::UserRole).toString());
        QSqlQuery query;
        query.exec(strQuery);
        strQuery = QString("delete from morphere where morpheregroup_id = " + item->data(Qt::UserRole).toString());
        query.exec(strQuery);
        RefreshMorphere(item->data(Qt::UserRole).toInt());
    }
    MorphereGroupRefresh();
}

void YMUploadWidget::MorphereGroupModify()
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");

    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }

    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        QString strQuery = QString("update morpheregroup set name = '" + m_pleMorphereGroup->text() +  "' where id = " + item->data(Qt::UserRole).toString());
        qDebug() << strQuery;
        db.exec(strQuery.toUtf8());
    }
    db.close();
    */
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        QString strQuery = QString("update morpheregroup set name = '" + m_pleMorphereGroup->text() +  "' where id = " + item->data(Qt::UserRole).toString());
        QSqlQuery query;
        query.exec(strQuery);
    }
    MorphereGroupRefresh();
}

void YMUploadWidget::MorphereGroupCopyPaste()
{
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        QSqlQuery query;
        QString strQuery = QString("insert into morpheregroup set "
                "name = '" + item->text() + "-'");
        query.exec(strQuery.toUtf8());
        query.exec("select max(id) from morpheregroup");
        if (query.next())
        {
            strQuery = QString("insert into morphere (type,data,morpheregroup_id) select type,data,");
            strQuery += query.value(0).toString();
            strQuery += " from morphere where morpheregroup_id = " + item->data(Qt::UserRole).toString();
            qDebug() << strQuery;
            query.exec(strQuery.toUtf8());
        }
    }
//    db.close();
    MorphereGroupRefresh();
}


void YMUploadWidget::MorphereGroupRefresh()
{
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    m_plwMorphereGroup->clear();
    QSqlQuery query("select id,name from morpheregroup");
    while (query.next())
    {
        QListWidgetItem *pItem = new QListWidgetItem(query.value(1).toString(),m_plwMorphereGroup);
        pItem->setData(Qt::UserRole, QVariant(query.value(0)));
    }
    //db.close();
}


void YMUploadWidget::RefreshMorphere(int _nGroup)
{
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    QSqlQuery query("select id,type,data from morphere where morpheregroup_id = " + QString::number(_nGroup));

    SJson json;
    m_plwMorphere->clear();
    while (query.next())
    {
        QString str;
        QString strJson = query.value(2).toString();

        QJsonObject jsonObj = QJsonDocument::fromJson(strJson.toUtf8()).object();

        str = STable::GetArticleType(json.Get(strJson,"Article").toInt());

        for(QJsonObject::iterator iterPos = jsonObj.begin(); iterPos != jsonObj.end(); iterPos++)
        {
            str += (" " + iterPos.key() + " : " + iterPos.value().toString() + " ,");
        }

        str = str.left(str.length() - 1);

        QListWidgetItem *pItem = new QListWidgetItem(str,m_plwMorphere);
        pItem->setData(Qt::UserRole, QVariant(query.value(0)));
    }
    //db.close();
}


void YMUploadWidget::currentGroupItemChanged(QListWidgetItem *_pCurrent, QListWidgetItem *_pPrev)
{
    Q_UNUSED(_pPrev);
    if (_pCurrent == 0) return;
    RefreshMorphere(_pCurrent->data(Qt::UserRole).toInt());
    m_pleMorphereGroup->setText(_pCurrent->text());
    m_pleMorphereGroup->repaint();
}



void YMUploadWidget::MorphereDelete()
{
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    foreach (QListWidgetItem *item,m_plwMorphere->selectedItems())
    {
        QString strQuery = QString("delete from morphere where id = '" + item->data(Qt::UserRole).toString() + "'");
        QSqlQuery query;
        query.exec(strQuery);
        //db.exec(strQuery.toUtf8());
    }
    //db.close();
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
        RefreshMorphere(item->data(Qt::UserRole).toInt());
}

void YMUploadWidget::MorphereAdd()
{
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
    {
        int nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
        DataBaseMorphereMorphere(((STable*)((Widget*)(m_ptwSource->currentWidget()))->GetTabWidget()->currentWidget())->getArticleSelect(), ((YMorphereWidget*)(m_ptwResult->currentWidget()))->convertToParam(), nCurrentFilterGroupID, E_DATABASE_COMMAND_INSERT);
    }
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
        RefreshMorphere(item->data(Qt::UserRole).toInt());
}



void YMUploadWidget::MorphereUp()
{
    int nSelect = m_plwMorphere->currentRow();
    if (nSelect <= 0) return;
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    QString strID1 = m_plwMorphere->item(nSelect)->data(Qt::UserRole).toString();
    QString strID2 = m_plwMorphere->item(nSelect-1)->data(Qt::UserRole).toString();
    QString strQuery = "UPDATE morphere t1 INNER JOIN Morphere t2 ON (t1.id, t2.id) IN ((" + strID1 + ","+ strID2 +"),("+ strID2 + "," + strID1 + ")) SET t1.type = t2.type,t1.morpheregroup_id = t2.morpheregroup_id,t1.data = t2.data";
    QSqlQuery query;
    query.exec(strQuery);
    //db.exec(strQuery.toUtf8());
    //db.close();
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
        RefreshMorphere(item->data(Qt::UserRole).toInt());

    m_plwMorphere->setCurrentRow(nSelect-1);
}

void YMUploadWidget::MorphereDown()
{
    int nSelect = m_plwMorphere->currentRow();
    if (nSelect < 0) return;
    if (nSelect >= (m_plwMorphere->count() - 1)) return;
    qDebug() << nSelect;
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");


    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    QString strID1 = m_plwMorphere->item(nSelect)->data(Qt::UserRole).toString();
    QString strID2 = m_plwMorphere->item(nSelect+1)->data(Qt::UserRole).toString();
    QString strQuery = "UPDATE morphere t1 INNER JOIN morphere t2 ON (t1.id, t2.id) IN ((" + strID1 + ","+ strID2 +"),("+ strID2 + "," + strID1 + ")) SET t1.type = t2.type,t1.morpheregroup_id = t2.morpheregroup_id,t1.data = t2.data";
    QSqlQuery query;
    query.exec(strQuery.toUtf8());
    //db.exec(strQuery.toUtf8());
    //db.close();
    foreach (QListWidgetItem *item,m_plwMorphereGroup->selectedItems())
        RefreshMorphere(item->data(Qt::UserRole).toInt());

    m_plwMorphere->setCurrentRow(nSelect+1);
}

void YMUploadWidget::DataBaseMorphereMorphere(int _nArticle,QMap<QString, QString> mapParam ,int _nGroup,int _nCommand, QString _strFilterId)
{
    QString strJson;
    SJson json;

    for(QMap<QString, QString>::iterator iterPos = mapParam.begin(); iterPos != mapParam.end(); iterPos++)
    {
        strJson = json.Set(strJson, iterPos.key(), iterPos.value());
    }

    DataBaseMorphere(_nArticle, json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}


void YMUploadWidget::DataBaseMorphere(int _nType, QString _strJson,int _nGroup,int _nCommand,QString _strFilterId)
{
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");



    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
*/
    QString sql;
    switch(_nCommand)
    {
    case E_DATABASE_COMMAND_INSERT:
        sql = "INSERT INTO morphere SET ";
        sql += QString("type=") + QString::number(_nType) + ",";
        break;
    case E_DATABASE_COMMAND_UPDATE:
        sql = "UPDATE morphere SET ";
        break;
    }
    sql += QString("data='") + _strJson + "',";
    sql += QString("morpheregroup_id=" ) + QString::number(_nGroup);
    if (_nCommand == E_DATABASE_COMMAND_UPDATE)
        sql += QString(" where id=") + _strFilterId;
    QSqlQuery query;
    if (query.exec(sql.toUtf8()) == false)
    {
        qDebug() << sql;
        qDebug() << query.lastError().text();
    }
  //  db.close();
}


void YMUploadWidget::currentMorphereItemChanged(QListWidgetItem *_pCurrent, QListWidgetItem *_pPrev)
{
    Q_UNUSED(_pPrev);
    if (_pCurrent == 0) return;
/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");



    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    */
    QSqlQuery query("select id,type,data from morphere where id = " + _pCurrent->data(Qt::UserRole).toString());
    if (!query.next()) return;
    SJson json;
    QString strJson = query.value(2).toString();
    qDebug() << json.Get(strJson, "Algorithm");
    qDebug() << m_ptwResult->count();

    for(int i = 0; i < m_ptwResult->count(); i++)
    {
        if(((YMorphereWidget*)(m_ptwResult->widget(i)))->getName() == json.Get(strJson, "Algorithm"))
        {

            ((YMorphereWidget*)(m_ptwResult->widget(i)))->setParam(strJson);
            m_ptwResult->setCurrentIndex(i);
            qDebug() << json.Get(strJson,"Algorithm");
        }
    }

    /*
    switch(query.value(1).toInt())
    {
    case E_FILTER_TYPE_DATE:
        m_pdeStart->setDate(QDate::fromString(json.Get(strJson,"Start"),"yyyy-MM-dd"));
        m_pdeEnd->setDate(QDate::fromString(json.Get(strJson,"End"),"yyyy-MM-dd"));
        m_pleString->setText("");
        m_pleLength->setText("");
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        break;
    case E_FILTER_TYPE_SEARCH:
        m_pcbCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbMethod->setCurrentIndex(json.GetNumber(strJson,"Method"));
        m_pcbKeyword->setCurrentIndex(json.GetNumber(strJson,"Keyword"));
        m_pleString->setText(json.Get(strJson,"String"));
        m_pleLength->setText("");
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        break;
    case E_FILTER_TYPE_LENGTH:
        m_pcbLengthCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbLengthComp->setCurrentIndex(json.GetNumber(strJson,"Comp"));
        m_pcbLengthInsDel->setCurrentIndex(json.GetNumber(strJson,"InsDel"));
        m_pleLength->setText(json.Get(strJson,"String"));
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        m_pleString->setText("");
        break;
    case E_FILTER_TYPE_REPLACE:
        m_pcbReplaceCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbReplaceFind->setCurrentIndex(json.GetNumber(strJson,"Find"));
        m_pleReplaceFind->setText(json.Get(strJson,"String_Find"));
        m_pleReplace->setText(json.Get(strJson,"String_Replace"));
        m_pleString->setText("");
        m_pleLength->setText("");
        break;
    case E_FILTER_TYPE_COUNTER:
        m_pcbCounterCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbCounterComp->setCurrentIndex(json.GetNumber(strJson,"Comp"));
        m_pcbCounterInsDel->setCurrentIndex(json.GetNumber(strJson,"InsDel"));
        m_pleCounter->setText(json.Get(strJson,"String"));
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        m_pleString->setText("");
        break;
    }
    */
}


void YMUploadWidget::setResultTabWidget(QTabWidget* tabWidget)
{
    m_ptwResult = tabWidget;
}

void YMUploadWidget::setSourceTabWidget(QTabWidget* tabWidget)
{
    m_ptwSource = tabWidget;
}

