#include "ymbasicwidget.h"
#include "../Json/sjson.h"
#include "../common.h"
#include <QGroupBox>
#include <QButtonGroup>
#include <QLabel>
#include <QSqlQuery>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QTextCodec>
#include <QMessageBox>
#include <QSqlError>
#include <QMenuBar>
#include <QInputDialog>


#define D_NOT_SELECT -1

#define SAFE_DELETE(x)       if(x != NULL) { delete x; x = NULL; }
#define SAFE_DELETEARRAY(x)  if(x != NULL) { delete [] x; x = NULL; }
#define SAFE_RELEASE(x)      if(x != NULL) { x->Release(); x = NULL; }


YMBasicWidget::YMBasicWidget(QWidget *parent)
    :YMorphereWidget(parent)
{
    if(!setListMorphere(m_strlistMorphere, m_strlistMorphereko))
    {
        m_strlistMorphere << "NNG" <<"NNP"<<"NNB"<<"NNBC"<<"NR"<<"NP"<<"VV"<<"VA"<<"VX"<<"VCP"<<"VCN"<<"MM"<<"MAG"<<"MAJ"<<"IC"<<"JKS"<<"JKC"<<"JKG"<<"JKO"<<"JKB"<<"JKV"<<"JKQ"<<"JX"<<"JC"<<"EP"<<"EF"<<"EC"<<"ETN"<<"ETM"<<"XPN"<<"XSN"<<"XSV"<<"XSA"<<"XR"<<"SF"<<"SE"<<"SSO"<<"SSC"<<"SC"<<"SY"<<"SL"<<"SH"<<"SN";
        m_strlistMorphereko << "NNG" <<"NNP"<<"NNB"<<"NNBC"<<"NR"<<"NP"<<"VV"<<"VA"<<"VX"<<"VCP"<<"VCN"<<"MM"<<"MAG"<<"MAJ"<<"IC"<<"JKS"<<"JKC"<<"JKG"<<"JKO"<<"JKB"<<"JKV"<<"JKQ"<<"JX"<<"JC"<<"EP"<<"EF"<<"EC"<<"ETN"<<"ETM"<<"XPN"<<"XSN"<<"XSV"<<"XSA"<<"XR"<<"SF"<<"SE"<<"SSO"<<"SSC"<<"SC"<<"SY"<<"SL"<<"SH"<<"SN";
    }

    m_strName = "basic";

    QVBoxLayout *vMainLayout = new QVBoxLayout;
    vMainLayout->setAlignment(Qt::AlignVCenter);
    QVBoxLayout *vboxlayout = new QVBoxLayout;

    QGroupBox *gBox = setMorphereList();
    QGroupBox *gDate = setDate();
    QGroupBox *gData = setData();
    QGroupBox *gFilter = setFilter();
    QGroupBox *gOther = setOther();
    QGroupBox *gSort = setSort();
    QHBoxLayout *hboxlayout = new QHBoxLayout;
    QGroupBox *gDictionary = setDictionary();
    QGroupBox *gCountMethod = setCountMethod();

    hboxlayout->addWidget(gBox,5);
    vboxlayout->addWidget(gData,3);
    vboxlayout->addWidget(gDate,3);

    //vboxlayout->addWidget(gFilter,3);
    vboxlayout->addWidget(gSort,2);
    vboxlayout->addWidget(gOther,2);
    vboxlayout->addWidget(gDictionary,2);
    vboxlayout->addWidget(gCountMethod,2);
    hboxlayout->addLayout(vboxlayout,5);

    vMainLayout->addLayout(hboxlayout, 2);

    m_ptwData = new QTabWidget;
    m_ptwData->setTabsClosable(true);
    connect(m_ptwData,SIGNAL(tabCloseRequested(int)),this,SLOT(CloseTab(int)));
    connect(m_ptwData,SIGNAL(tabBarDoubleClicked(int)),this,SLOT(DoubleClickTab(int)));
    AddTable("Start");

    vMainLayout->addWidget(m_ptwData, 8);
    setLayout(vMainLayout);
}

QGroupBox *YMBasicWidget::setMorphereList()
{
    QVBoxLayout *vlayout = new QVBoxLayout;
    QVBoxLayout *vlayout1 = new QVBoxLayout;

    QHBoxLayout *hlayout = new QHBoxLayout;
    QGroupBox *groupBox = new QGroupBox(tr("Morphere List"));

    m_plwMorphereList = new QListWidget;
    m_plwMorphereAdd  = new QListWidget;
    m_plwMorphereList->setSelectionMode(QAbstractItemView::MultiSelection);
    m_plwMorphereAdd->setSelectionMode(QAbstractItemView::ExtendedSelection);


    for(int i=0;i<m_strlistMorphere.size();i++)
    {
        QListWidgetItem* pitem = new QListWidgetItem(m_strlistMorphereko.at(i), m_plwMorphereList);
        pitem->setData(Qt::UserRole, QVariant(m_strlistMorphere.at(i)));
    }

    for(int i=0;i<m_strlistMorphere.size();i++)
    {
        QListWidgetItem* pitem = new QListWidgetItem(m_strlistMorphereko.at(i), m_plwMorphereAdd);
        pitem->setData(Qt::UserRole, QVariant(m_strlistMorphere.at(i)));
    }

    for(int i=0;i<m_plwMorphereAdd->count();i++)
    {
        m_plwMorphereAdd->item(i)->setHidden(true);
    }


    QPushButton *ppbAdd = new QPushButton("Add");
    QPushButton *ppbDel = new QPushButton("Del");
    vlayout->addWidget(m_plwMorphereList);
    vlayout->addWidget(ppbAdd);

    vlayout1->addWidget(m_plwMorphereAdd);
    vlayout1->addWidget(ppbDel);

    connect(ppbAdd, SIGNAL(released()),this, SLOT(MorphereListAdd()));
    connect(ppbDel, SIGNAL(released()),this, SLOT(MorphereListDel()));



    hlayout->addLayout(vlayout);
    hlayout->addLayout(vlayout1);

    groupBox->setLayout(hlayout);
    groupBox->setCheckable(true);
    return groupBox;
}


QGroupBox *YMBasicWidget::setDate()
{
    QHBoxLayout *hlayout = new QHBoxLayout;
    QHBoxLayout *hlayout1 = new QHBoxLayout;
    QHBoxLayout *hlayout2 = new QHBoxLayout;
    QVBoxLayout *vlayout = new QVBoxLayout;

    QGroupBox *groupBox = new QGroupBox(tr("Date"));

    m_pdeStart = new QDateEdit(QDate::currentDate());
    m_pdeEnd = new QDateEdit(QDate::currentDate());

    m_pdeStart->setDateRange(QDate(2003, 5, 20),QDate::currentDate());
    m_pdeEnd->setDateRange(QDate(2003, 5, 20),QDate::currentDate());

    QCalendarWidget *pCalender = new QCalendarWidget();
    m_pdeStart->setCalendarWidget(pCalender);
    m_pdeStart->setCalendarPopup(true);

    m_pdeEnd->setCalendarWidget(pCalender);
    m_pdeEnd->setCalendarPopup(true);

    m_pcbDate = new QComboBox;
    m_pcbDate->addItems(QStringList() << "ALL" << "NotAll");

    m_pcbPeriod = new QComboBox;
    m_pcbPeriod->addItems(QStringList() << "None" << "1 Day" << "1 Week" << "1 Month");

    m_pleDates = new QLineEdit;
    m_pleDates->setValidator(new QIntValidator(1, 100));


    m_pcbDuring = new QComboBox;
    m_pcbDuring->addItems(QStringList() << "None" << "Days" << "Weeks" << "Months" << "Years");

    hlayout->addWidget(m_pcbDate);
    hlayout->addWidget(new QLabel("Start:"));
    hlayout->addWidget(m_pdeStart);
    hlayout->addWidget(new QLabel("End:"));
    hlayout->addWidget(m_pdeEnd);

    hlayout1->addWidget(new QLabel("Period:"));
    hlayout1->addWidget(m_pcbPeriod);

    hlayout2->addWidget(new QLabel("Recent:"));
    hlayout2->addWidget(m_pleDates);
    hlayout2->addWidget(m_pcbDuring);

    vlayout->addLayout(hlayout2);
    vlayout->addLayout(hlayout);
    vlayout->addLayout(hlayout1);

    groupBox->setCheckable(true);

    groupBox->setLayout(vlayout);

    return groupBox;
}

QGroupBox *YMBasicWidget::setData()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbData = new QComboBox;
    m_pcbData->addItems(QStringList() << "Title" << "Body" << "Title+Body" << "PlatformTitle");

    m_pcbData->setCurrentIndex(2);

    hlayout->addWidget(new QLabel("Data: "));
    hlayout->addWidget(m_pcbData);


    QGroupBox *groupBox = new QGroupBox(tr("Data"));

    groupBox->setCheckable(true);
    groupBox->setLayout(hlayout);
    groupBox->setChecked(true);
    return groupBox;
}

QGroupBox *YMBasicWidget::setCountMethod()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbCountMethod = new QComboBox;
    m_pcbCountMethod->addItems(QStringList() << "Duplicate" << "NonDuplicate");

    hlayout->addWidget(new QLabel("CountMethod: "));
    hlayout->addWidget(m_pcbCountMethod);


    QGroupBox *groupBox = new QGroupBox(tr("CountMethod"));

    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);
    groupBox->setChecked(true);
    return groupBox;
}


QGroupBox *YMBasicWidget::setFilter()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pleKeyword = new QLineEdit;
    m_pleTop = new QLineEdit;

    hlayout->addWidget(new QLabel("Top: <"));
    hlayout->addWidget(m_pleTop);
    hlayout->addWidget(new QLabel("Keyword:"));
    hlayout->addWidget(m_pleKeyword);

    QGroupBox *groupBox = new QGroupBox(tr("Filter"));

    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);
    groupBox->setChecked(false);
    return groupBox;
}

QGroupBox *YMBasicWidget::setOther()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbThread = new QComboBox;

    hlayout->addWidget(new QLabel("Thread:"));
    hlayout->addWidget(m_pcbThread);

    m_pcbThread->addItems(QStringList() << "1" <<  "2" << "4" << "8");

    QGroupBox *groupBox = new QGroupBox(tr("Other"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}

QGroupBox *YMBasicWidget::setSort()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_rbDateMorphere = new QRadioButton("Date/Morphere");
    m_rbMorphereDate = new QRadioButton("Morphere/Date");


    m_bgRadioGroup = new QButtonGroup;

    m_bgRadioGroup->addButton(m_rbMorphereDate);
    m_bgRadioGroup->addButton(m_rbDateMorphere);

    m_rbMorphereDate->setChecked(true);

    hlayout->addWidget(m_rbMorphereDate);
    hlayout->addWidget(m_rbDateMorphere);

    QGroupBox *groupBox = new QGroupBox(tr("Sort"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}


QGroupBox *YMBasicWidget::setDictionary()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbDictionary = new QComboBox;

    m_pcbDictionary->setEditable(true);
    m_pcbDictionary->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    QPushButton* add = new QPushButton;
    QPushButton* del = new QPushButton;
    add->setText(tr("+"));
    del->setText(tr("-"));

    //hlayout->addWidget(new QLabel(tr("User-Dict: ")));
    hlayout->addWidget(m_pcbDictionary);
    hlayout->addWidget(add);
    hlayout->addWidget(del);

    connect(add, SIGNAL(released()),this, SLOT(AddDictionary()));
    connect(del, SIGNAL(released()),this, SLOT(DelDictionary()));

    QGroupBox *groupBox = new QGroupBox(tr("User Dictionary"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}

void YMBasicWidget::AddDictionary()
{
    QStringList strFilenames = QFileDialog::getOpenFileNames(0,"Dictionary file",QDir::currentPath(),
            "dic files (*.dic);;All files (*.*)",new QString("Dictionary files (*.dic)"));

    foreach(QString strFilename, strFilenames)
    {
        QFile file(strFilename);
        if (!file.open(QIODevice::ReadOnly)) return;
    }


    for(int i = 0; i < m_pcbDictionary->count(); i++)
    {
        if(strFilenames.contains(m_pcbDictionary->itemText(i)))
            strFilenames.removeOne(m_pcbDictionary->itemText(i));
    }

    m_pcbDictionary->addItems(strFilenames);
}

QString YMBasicWidget::getUserDictList()
{
    QStringList strList;

    for(int i = 0; i < m_pcbDictionary->count();i++)
    {
        strList << m_pcbDictionary->itemText(i);
    }

    return strList.join(",");
}



void YMBasicWidget::DelDictionary()
{
    m_pcbDictionary->removeItem(0);
    qDebug() << getUserDictList();
}

bool YMBasicWidget::isSortMorphereDateChecked()
{
    return m_rbMorphereDate->isChecked();
}

bool YMBasicWidget::isSortDateMorphereChecked()
{
    return m_rbDateMorphere->isChecked();
}


void YMBasicWidget::MorphereListAdd()
{
    QList<QListWidgetItem *> listitem = m_plwMorphereList->selectedItems();

    foreach(QListWidgetItem *item, listitem)
    {
        for(int i = 0; i < m_plwMorphereAdd->count();i++)
        {
            if(item->data(Qt::UserRole) == m_plwMorphereAdd->item(i)->data(Qt::UserRole))
                m_plwMorphereAdd->item(i)->setHidden(false);
        }
    }
}

void YMBasicWidget::MorphereListDel()
{
    for(int i = m_plwMorphereAdd->count() - 1; i >= 0 ;i--)
    {
        if(m_plwMorphereAdd->item(i)->isSelected())
        {
            m_plwMorphereAdd->item(i)->setHidden(true);
        }
    }
}

QTableWidget *YMBasicWidget::AddTable(QString _str)
{
    STable *pTable = new STable;
    m_ptwData->addTab(pTable,_str);
    return (QTableWidget *)pTable;
}

void YMBasicWidget::CloseTab(int index)
{
    ((STable*)(m_ptwData->widget(index)))->clear();
    m_ptwData->removeTab(index);
}

void YMBasicWidget::DoubleClickTab(int index)
{
    bool ok;
    if (index < 0) return;
    QString text = QInputDialog::getText(this,"Tab name change","Name : ", QLineEdit::Normal,m_ptwData->tabText(index), &ok);
    if (ok)
    {
        m_ptwData->setTabText(index,text);
    }
}

void YMBasicWidget::FileImport()
{
    QString strFilename = QFileDialog::getOpenFileName(0,"Import file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));

    QFile file(strFilename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;

    clearResult();
    m_mapViewResult.clear();

    //qDebug() << "clear is complete";

    QTextStream in(&file);

    while(!in.atEnd())
    {
        QString strLine = in.readLine();
        strLine = strLine.replace("\"","");
        //qDebug() << strLine;
        QStringList strListLine = strLine.split(",");

        if(strListLine.size() != 4)
            continue;

        //qDebug() << strListLine.at(4).trimmed().toInt();

        QString strKey = strListLine.at(0).trimmed() + "~!@" + strListLine.at(1).trimmed() + "~!@" + strListLine.at(2).trimmed();
        m_mapResult.insert(strKey, strListLine.at(3).trimmed().toInt());
    }

    file.close();

    for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
    {
        QString strkey = iterPos.key();
        int count = iterPos.value();
        QStringList strlistKey = strkey.split("~!@");
        QString strDate = strlistKey.at(0);
        QString strMorphere = strlistKey.at(1);
        QString strKeyword = strlistKey.at(2);

        if(m_mapViewResult.contains(strDate))
        {
            if(m_mapViewResult.value(strDate).contains(strMorphere))
            {
                m_mapViewResult[(strDate)][(strMorphere)].insertMulti(count, strKeyword);
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count, strKeyword);
                m_mapViewResult[(strDate)].insert(strMorphere, qLast);
            }
        }
        else
        {
            QMap<int, QString> qLast;
            qLast.insert(count , strKeyword);
            QMap<QString, QMap<int, QString> > qMedium;
            qMedium.insert(strMorphere, qLast);
            m_mapViewResult.insert(strDate, qMedium);
        }
    }
    ViewResult();
}

void YMBasicWidget::SaveFile()
{
    /*
    QString strFilename = QFileDialog::getSaveFileName(0,"save file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";
    QFile file(strFilename);
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    STable* pTable = (STable*)((QTabWidget*)(m_ptwTable->currentWidget()))->currentWidget();
    int nCountIndex = pTable->columnCount() - 1;
    int nKeywordIndex = pTable->columnCount() - 2;

    QString strCKeyword = m_pleCKeyword->text().trimmed();
    for (int i = 0; i < pTable->rowCount(); i++)
    {
        QString strKeyword = pTable->item(i, nKeywordIndex)->text().trimmed();
        int nCount = pTable->item(i, nCountIndex)->text().trimmed().toInt();
        for(int j = 0; j < nCount; j++)
        {
            out << strCKeyword << ";" << strKeyword << endl;
        }
    }
    file.close();
    */
    FileExport();
}


void YMBasicWidget::FileExport()
{
    QString strFilename = QFileDialog::getSaveFileName(0,"Exoprt file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";
    QFile file(strFilename);
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);


    for (int i = 0; i < m_ptwData->count(); i++)
    {
        m_ptwData->setTabEnabled(i, true);
        QTabWidget* p_childWidget = (QTabWidget*)(m_ptwData->widget(i));

        for (int j = 0; j < p_childWidget->count(); j++)
        {
            p_childWidget->setTabEnabled(j, true);
            STable *stable = (STable *) (p_childWidget->widget(j));
            for (int nCount = 0 ; nCount < stable->rowCount(); nCount++ )
            {

                QString str = stable->item(nCount,0)->text().trimmed() + "," +  stable->item(nCount,1)->text().trimmed();
                out << m_ptwData->tabText(i).trimmed() << "," << p_childWidget->tabText(j).trimmed() << ",";
                out << str << endl;
            }
        }
    }

    file.close();
}

int YMBasicWidget::getThread()
{
    return m_pcbThread->currentText().toInt();
}


unsigned int YMBasicWidget::getDateStart()
{
    return m_pdeStart->dateTime().toString("yyyy-MM-dd").replace("-","").trimmed().toInt();
}

unsigned int YMBasicWidget::getDateEnd()
{
    return m_pdeEnd->dateTime().toString("yyyy-MM-dd").replace("-","").trimmed().toInt();
}

int YMBasicWidget::getPeriod()
{
    return m_pcbPeriod->currentIndex();
}

QStringList YMBasicWidget::getMorphereList()
{
    QStringList strList;
    for(int i = 0; i < m_plwMorphereAdd->count();i++)
    {
        if(m_plwMorphereAdd->item(i)->isHidden())
            continue;
        else
        {
            strList << m_plwMorphereAdd->item(i)->data(Qt::UserRole).toString();
        }
    }
    return strList;
}

bool YMBasicWidget::getDateAll()
{
    if(m_pcbDate->currentIndex() == 0)
        return true;
    else
        return false;
}

QTabWidget* YMBasicWidget::getQTabWidget()
{
      return m_ptwData;
}


void YMBasicWidget::MemClear()
{
    m_mapResult.clear();
    m_mapViewResult.clear();
}


bool YMBasicWidget::setListMorphere(QStringList& MorphereEN, QStringList& MorphereKO)
{
    QFile fHeader("morpherelist.txt");
    if (!fHeader.open(QIODevice::ReadOnly | QIODevice::Text)) return false;

    QTextStream in(&fHeader);

    QString str = in.readLine();

    if(str.at(0) == '#')
    {
    }
    else
    {
        qDebug() << "The wrong file is read";
        return false;
    }

    while(!in.atEnd())
    {
        str = in.readLine();
        QStringList strList = str.trimmed().split("@",QString::SkipEmptyParts);
        if(strList.isEmpty())
            break;
        if(strList.size() < 2)
            return false;
        MorphereEN << strList.at(0).trimmed().replace("\"","").trimmed();
        MorphereKO << strList.at(1).trimmed().replace("\"","").trimmed();
    }

    return true;
}


void YMBasicWidget::SaveFileSimple()
{
    RawFileExport();
}



void YMBasicWidget::RawFileExport()
{
    QString strFilename = QFileDialog::getSaveFileName(0,"Exoprt file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";
    QFile file(strFilename);
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    /*
    out << "#Head#,";
    for (int nCount = 0;nCount < pCurrent->columnCount() ;nCount++ )
        out << pCurrent->horizontalHeaderItem(nCount)->text() << ",";

    m_pProgress->setRange(0,pCurrent->rowCount()-1);
    */

    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++)
    {
        for(QMap<QString, QMap<int, QString> >::iterator iterPos2 = iterPos.value().begin(); iterPos2 != iterPos.value().end(); iterPos2++)
        {
            QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
            i.toBack();
            while(i.hasPrevious())
            {
                i.previous();
                out << "\"" << iterPos.key() << "\"" << ",";
                out << "\"" << iterPos2.key() << "\"" << ",";
                out << "\"" << i.value() << "\"" << ",";
                out << "\"" << i.key() << "\"" << "\n";
            }
        }
    }

    file.close();
}



YMBasicWidget::~YMBasicWidget()
{

}

void YMBasicWidget::clearViewResult()
{

}



void YMBasicWidget::clearView()
{
    m_mapViewResult.clear();
}

void YMBasicWidget::setParam(QString strJson)
{

    SJson json;
    {

        QString strMorphere = json.Get(strJson, "MorphereList");
        QStringList slMorphere = strMorphere.split(" ", QString::SkipEmptyParts);

        for(int i = 0; i < m_plwMorphereAdd->count(); i++)
        {
            m_plwMorphereAdd->item(i)->setHidden(true);
        }

        for(int i = 0; i < m_plwMorphereAdd->count(); i++)
        {
            foreach(QString morphere, slMorphere)
            {
                if(m_plwMorphereAdd->item(i)->data(Qt::UserRole).toString().compare(morphere, Qt::CaseInsensitive) == 0)
                {
                    m_plwMorphereAdd->item(i)->setHidden(false);
                }
            }
        }
    }

    {
        int nThread = json.Get(strJson, "Thread").toInt();
        for(int i = 0; i < m_pcbThread->count(); i++)
        {
            //qDebug() << m_pcbThread->itemData(i).toInt();
            if(m_pcbThread->itemText(i).trimmed().toInt() == nThread)
            {
                m_pcbThread->setCurrentIndex(i);
                break;
            }
        }
    }

    {
        QString strCountMethod = json.Get(strJson, "CountMethod").trimmed();
        for(int i = 0; i < m_pcbCountMethod->count(); i++)
        {
            //qDebug() << m_pcbThread->itemData(i).toInt();
            if(m_pcbCountMethod->itemText(i).trimmed().compare(strCountMethod) == 0)
            {
                m_pcbCountMethod->setCurrentIndex(i);
                break;
            }
        }
    }

    {
        QString strRecentPeriod = json.Get(strJson, "RecentPeriod").trimmed();
        for(int i = 0; i < m_pcbDuring->count(); i++)
        {
            //qDebug() << m_pcbThread->itemData(i).toInt();
            if(m_pcbDuring->itemText(i).trimmed().compare(strRecentPeriod) == 0)
            {
                m_pcbDuring->setCurrentIndex(i);
                break;
            }
        }
    }
    {
        int nPeriod = json.Get(strJson, "Period").toInt();
        m_pcbPeriod->setCurrentIndex(nPeriod);
    }
    {
        int nBodyTitle = json.Get(strJson, "TitleBody").toInt();
        m_pcbData->setCurrentIndex(nBodyTitle);
    }
    {
        QString strDateAll = json.Get(strJson, "DateALL").trimmed();
        if(strDateAll.compare("true",Qt::CaseInsensitive) == 0)
        {
            m_pcbDate->setCurrentIndex(0);
        }
        else
        {
            m_pcbDate->setCurrentIndex(1);
        }
    }
    {
        QString strRecentDate = json.Get(strJson, "RecentDate");
        m_pleDates->setText(strRecentDate);
    }
    {

        m_pdeStart->setDate(QDate::fromString(json.Get(strJson,"DateStart"),"yyyyMMdd"));
        m_pdeEnd->setDate(QDate::fromString(json.Get(strJson,"DateEnd"),"yyyyMMdd"));
    }
    {
        QString userdict = json.Get(strJson, "UserDict");
        if(!userdict.isEmpty())
        {

            m_pcbDictionary->clear();
            QStringList sluserdict = userdict.split(",");
            foreach(QString dict, sluserdict)
            {
                m_pcbDictionary->addItem(dict);
            }
        }
        else
        {
            m_pcbDictionary->clear();
        }
    }
}


void YMBasicWidget::SortViewResult()
{
    /*
     * origian source
    if(isSortDateMorphereChecked())
    {
        for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);

            if(m_mapViewResult.contains(strDate))
            {
                if(m_mapViewResult.value(strDate).contains(strMorphere))
                {
                    m_mapViewResult[(strDate)][(strMorphere)].insertMulti(count, strKeyword);
                }
                else
                {
                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strDate)].insert(strMorphere, qLast);
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strMorphere, qLast);
                m_mapViewResult.insert(strDate, qMedium);
            }
        }
    }
    else
    {
        for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);

            if(m_mapViewResult.contains(strMorphere))
            {
                if(m_mapViewResult.value(strMorphere).contains(strDate))
                {
                    m_mapViewResult[(strMorphere)][(strDate)].insertMulti(count, strKeyword);
                }
                else
                {
                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strMorphere)].insert(strDate, qLast);
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strDate, qLast);
                m_mapViewResult.insert(strMorphere, qMedium);
            }
        }
    }
    */


    if(isSortDateMorphereChecked())
    {
        for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);
            m_mapViewResult[(strDate)]["ALLMORPHERE"].insertMulti(count, QString(strMorphere + "~!@" + strKeyword )); // added
            if(m_mapViewResult.contains(strDate))
            {
                if(m_mapViewResult.value(strDate).contains(strMorphere))
                {
                    m_mapViewResult[(strDate)][(strMorphere)].insertMulti(count, strKeyword);
                    //m_mapViewResult[(strDate)]["ALLMORPHERE"].insertMulti(count, QString(strMorphere + "~!@" + strKeyword )); // added
                }
                else
                {
                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strDate)].insert(strMorphere, qLast);

                    /*
                    qLast.clear(); //added
                    qLast.insert(count, QString(strMorphere + "~!@" + strKeyword));//added
                    m_mapViewResult[(strDate)].insert("ALLMORPHERE", qLast);//added
                    */
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strMorphere, qLast);
                m_mapViewResult.insert(strDate, qMedium);
                /*
                qLast.clear();
                qMedium.clear();
                qLast.insert(count, QString(strMorphere + "~!@" + strKeyword));
                qMedium.insert("ALLMORPHERE", qLast);
                m_mapViewResult.insert(strDate, qMedium);
                */
            }
        }
    }
    else
    {
        for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);
            m_mapViewResult[("ALLMORPHERE")][(strDate)].insertMulti(count, QString(strMorphere + "~!@" + strKeyword ));
            if(m_mapViewResult.contains(strMorphere))
            {
                if(m_mapViewResult.value(strMorphere).contains(strDate))
                {
                    m_mapViewResult[(strMorphere)][(strDate)].insertMulti(count, strKeyword);
                    //m_mapViewResult[("ALLMORPHERE")][(strDate)].insertMulti(count, QString(strMorphere + "~!@" + strKeyword ));
                }
                else
                {

                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strMorphere)].insert(strDate, qLast);
                    /*
                    qLast.clear();
                    qLast.insert(count, QString(strMorphere + "~!@" + strKeyword) );
                    m_mapViewResult[("ALLMORPHERE")].insert(strDate, qLast);
                    */
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strDate, qLast);
                m_mapViewResult.insert(strMorphere, qMedium);
                /*
                qLast.clear();
                qMedium.clear();
                qLast.insert(count,QString(strMorphere + "~!@" + strKeyword));
                qMedium.insert(strDate, qLast);
                m_mapViewResult.insert("ALLMORPHERE", qMedium);
                */
           }
        }
    }
/*
    for(QMap<QString, int>::iterator iterPos = m_mapResult.begin(); iterPos != m_mapResult.end(); iterPos++)
    {
        QString strkey = iterPos.key();
        int count = iterPos.value();
        QStringList strlistKey = strkey.split("~!@");
        QString strDate = strlistKey.at(0);
        QString strMorphere = strlistKey.at(1);
        QString strKeyword = strlistKey.at(2);

        if(m_mapViewResult2.contains(strDate))
        {
            if(m_mapViewResult2.value(strDate).contains(count))
            {
                m_mapViewResult2[(strDate)][(count)].insertMulti(strMorphere, strKeyword);
            }
            else
            {
                QMap<QString, QString> qLast;
                qLast.insert(strMorphere, strKeyword);
                m_mapViewResult2[(strDate)].insert(count, qLast);
            }
        }
        else
        {
            QMap<QString, QString> qLast;
            qLast.insert(strMorphere , strKeyword);
            QMap<int, QMap<QString, QString> > qMedium;
            qMedium.insert(count, qLast);
            m_mapViewResult2.insert(strDate, qMedium);
        }
    }
*/
}






void YMBasicWidget::ViewResult()
{
    /*
    SortViewResult();
    foreach(STable* ptable, m_lTable)
    {
        ptable->clear();
        delete ptable;
    }
    m_lTable.clear();

    foreach(QTabWidget* pwidget, m_lTabWidget)
    {
        pwidget->clear();
        delete pwidget;
    }
    m_lTabWidget.clear();


    m_ptwTable = getQTabWidget();
    m_ptwTable->clear();

    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++)
    {
        QTabWidget* temp = new QTabWidget;
        for(QMap<QString, QMap<int, QString> >::iterator iterPos2 = iterPos.value().begin(); iterPos2 != iterPos.value().end(); iterPos2++)
        {
            int ncRow = 0;

            STable *pNew = new STable;
            pNew->setColumnCount(2);
            pNew->setRowCount(m_mapViewResult[iterPos.key()][iterPos2.key()].size());
            pNew->setHorizontalHeaderItem(0 ,new QTableWidgetItem("Keyword"));
            pNew->setHorizontalHeaderItem(1 ,new QTableWidgetItem("Count"));

            QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
            i.toBack();
            while(i.hasPrevious())
            {
                i.previous();
                pNew->setItem(ncRow,0,new QTableWidgetItem(QString(i.value())));
                pNew->setItem(ncRow,1,new QTableWidgetItem(QString::number(i.key())));
                ncRow++;
            }
            temp->addTab(pNew, iterPos2.key());
            m_lTable << pNew;
        }
        m_ptwTable->addTab(temp, iterPos.key());
        m_lTabWidget << temp;
    }
    */

    SortViewResult();
    foreach(STable* ptable, m_lTable)
    {
        ptable->clear();
        delete ptable;
    }
    m_lTable.clear();

    foreach(QTabWidget* pwidget, m_lTabWidget)
    {
        pwidget->clear();
        delete pwidget;
    }
    m_lTabWidget.clear();


    m_ptwTable = getQTabWidget();
    m_ptwTable->clear();

    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++)
    {
        QTabWidget* temp = new QTabWidget;
        for(QMap<QString, QMap<int, QString> >::iterator iterPos2 = iterPos.value().begin(); iterPos2 != iterPos.value().end(); iterPos2++)
        {

            if( (iterPos2.key() == "ALLMORPHERE") || (iterPos.key() == "ALLMORPHERE") )
            {
                int ncRow = 0;

                STable *pNew = new STable;
                pNew->setColumnCount(3);
                pNew->setRowCount(m_mapViewResult[iterPos.key()][iterPos2.key()].size());
                pNew->setHorizontalHeaderItem(0 ,new QTableWidgetItem("Morphere"));
                pNew->setHorizontalHeaderItem(1 ,new QTableWidgetItem("Keyword"));
                pNew->setHorizontalHeaderItem(2 ,new QTableWidgetItem("Count"));

                QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
                i.toBack();
                while(i.hasPrevious())
                {
                    i.previous();
                    pNew->setItem(ncRow,0,new QTableWidgetItem(QString(i.value().split("~!@").at(0))));
                    pNew->setItem(ncRow,1,new QTableWidgetItem(QString(i.value().split("~!@").at(1))));
                    pNew->setItem(ncRow,2,new QTableWidgetItem(QString::number(i.key())));
                    ncRow++;
                }
                temp->addTab(pNew, iterPos2.key());
                m_lTable << pNew;

            }
            else
            {
                int ncRow = 0;

                STable *pNew = new STable;
                pNew->setColumnCount(2);
                pNew->setRowCount(m_mapViewResult[iterPos.key()][iterPos2.key()].size());
                pNew->setHorizontalHeaderItem(0 ,new QTableWidgetItem("Keyword"));
                pNew->setHorizontalHeaderItem(1 ,new QTableWidgetItem("Count"));

                QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
                i.toBack();
                while(i.hasPrevious())
                {
                    i.previous();
                    pNew->setItem(ncRow,0,new QTableWidgetItem(QString(i.value())));
                    pNew->setItem(ncRow,1,new QTableWidgetItem(QString::number(i.key())));
                    ncRow++;
                }
                temp->addTab(pNew, iterPos2.key());
                m_lTable << pNew;
            }

        }
        m_ptwTable->addTab(temp, iterPos.key());
        m_lTabWidget << temp;
    }
}

QMap<QString, QString> YMBasicWidget::convertToParam()
{
    QMap<QString, QString> mapParam;
    mapParam.insert("Algorithm", "basic");

    {
        QString strMorphereList = getMorphereList().join(" ");
        mapParam.insert("MorphereList",strMorphereList);
    }
    {
        int nThread = getThread();
        mapParam.insert("Thread", QString::number(nThread));
    }
    {
        QString strUserDict = getUserDictList();
        if(strUserDict.trimmed().length() > 0)
            mapParam.insert("UserDict", strUserDict);
    }
    {
        if(getDateAll())
            mapParam.insert("DateALL", "true");
        else
            mapParam.insert("DateALL", "false");
    }
    {
        mapParam.insert("DateStart", QString::number(getDateStart()));
        mapParam.insert("DateEnd", QString::number(getDateEnd()));
    }
    {
        mapParam.insert("Period", QString::number(getPeriod()));
    }
    {
        mapParam.insert("CountMethod", m_pcbCountMethod->currentText().trimmed());
    }
    {
        mapParam.insert("RecentDate", m_pleDates->text().trimmed());
        mapParam.insert("RecentPeriod", m_pcbDuring->currentText().trimmed());
    }
    {
        mapParam.insert("TitleBody", QString::number(m_pcbData->currentIndex()));
    }
    {
        mapParam.insert("Article",QString::number(((STable *)m_pTabWidget->currentWidget())->getArticleSelect()));
    }


    return mapParam;
}
