
#include "ymonedepthwidget.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>
#include <QIntValidator>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QUrl>
#include <QDir>
#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; }


YMOneDepthWidget::YMOneDepthWidget(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 = "onedepth";

    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 *gCenterKeyword = setCenterKeyword();

    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);

    hboxlayout->addLayout(vboxlayout,5);
    vMainLayout->addLayout(hboxlayout, 2);

    vMainLayout->addWidget(gCenterKeyword, 1);
    vMainLayout->addWidget(gFilter, 1);

    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 *YMOneDepthWidget::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 *YMOneDepthWidget::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 *YMOneDepthWidget::setFilter()
{
    QHBoxLayout *hlayout = new QHBoxLayout;
    QHBoxLayout *hlayout2 = new QHBoxLayout;
    QHBoxLayout *hlayout3 = new QHBoxLayout;
    QVBoxLayout *vlayout = new QVBoxLayout;


    m_pleFilterRankALL = new QLineEdit;
    m_pleFilterRankSeparated = new QLineEdit;
    m_pleFilterKeyword = new QLineEdit;
    m_pleFilterKeywordLength = new QLineEdit;
    m_pleFilterExtractor = new QLineEdit;

    m_pleFilterKeywordLength->setValidator(new QIntValidator(1, 10));
    m_pleFilterRankALL->setValidator(new QIntValidator(1, 10000));
    m_pleFilterRankSeparated->setValidator(new QIntValidator(1, 10000));

    hlayout->addWidget(new QLabel("RankALL: "));
    hlayout->addWidget(m_pleFilterRankALL);
    hlayout->addWidget(new QLabel("RankSeparated: "));
    hlayout->addWidget(m_pleFilterRankSeparated);
    hlayout->addWidget(new QLabel("Keyword Length: "));
    hlayout->addWidget(m_pleFilterKeywordLength);

    hlayout2->addWidget(new QLabel("KeywordFilter: "));
    hlayout2->addWidget(m_pleFilterKeyword);

    hlayout3->addWidget(new QLabel("Extract Keyword: "));
    hlayout3->addWidget(m_pleFilterExtractor);


    vlayout->addLayout(hlayout3);
    vlayout->addLayout(hlayout2);
    vlayout->addLayout(hlayout);
    QGroupBox *groupBox = new QGroupBox(tr("Filter"));

    groupBox->setCheckable(true);

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

QGroupBox *YMOneDepthWidget::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 *YMOneDepthWidget::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 *YMOneDepthWidget::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;
}


QGroupBox *YMOneDepthWidget::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 *YMOneDepthWidget::setCenterKeyword()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

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


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

    QGroupBox *groupBox = new QGroupBox(tr("Center Keyword"));

    groupBox->setCheckable(true);

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


void YMOneDepthWidget::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 YMOneDepthWidget::getUserDictList()
{
    QStringList strList;

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

    return strList.join(",");
}



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

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

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


void YMOneDepthWidget::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 YMOneDepthWidget::MorphereListDel()
{
    for(int i = m_plwMorphereAdd->count() - 1; i >= 0 ;i--)
    {
        if(m_plwMorphereAdd->item(i)->isSelected())
        {
            m_plwMorphereAdd->item(i)->setHidden(true);
        }
    }
}

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

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

void YMOneDepthWidget::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 YMOneDepthWidget::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 YMOneDepthWidget::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 YMOneDepthWidget::getThread()
{
    return m_pcbThread->currentText().toInt();
}


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

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

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

QStringList YMOneDepthWidget::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 YMOneDepthWidget::getDateAll()
{
    if(m_pcbDate->currentIndex() == 0)
        return true;
    else
        return false;
}

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


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

void YMOneDepthWidget::D3View()
{
    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    /*
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";
    */
    QString strjson = "{\"name\":\" " + strCKeyword + "\",";
    strjson += ("\"children\": [");

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

    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();
        strjson += ("{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "]}";

    QString strHtml;

    strHtml = "<!DOCTYPE html>"
              "\n<head>"
              "\n<meta charset=\"utf8\">"
              "\n<style>"
              "\n"
              "\n.node circle {"
              "\n  cursor: pointer;"
              "\n  stroke: #3182bd;"
              "\n  stroke-width: 1.5px;"
              "\n}"
              "\n"
              "\n.node text {"
              "\n  font: 14px sans-serif;"
              "\n  pointer-events: none;"
              "\n  text-anchor: middle;"
              "\n}"
              "\n"
              "\nline.link {"
              "\n  fill: none;"
              "\n  stroke: #9ecae1;"
              "\n  stroke-width: 1.5px;"
              "\n}"
              "\n"
              "\n</style>"
              "\n</head>"
              "\n<body>"
              "\n<script src=\"http://d3js.org/d3.v3.min.js\"></script>"
              "\n<script>"
              "\n"
              "\nvar width = 1920,"
              "\n    height = 1080,"
              "\n    root;"
              "\n"
              "\nvar force = d3.layout.force()"
              "\n    .linkDistance(80)"
              "\n    .charge(-120)"
              "\n    .gravity(.05)"
              "\n    .size([width, height])"
              "\n    .on(\"tick\", tick);"
              "\n"
              "\nvar svg = d3.select(\"body\").append(\"svg\")"
              "\n    .attr(\"width\", width)"
              "\n    .attr(\"height\", height);"
              "\n"
              "\nvar link = svg.selectAll(\".link\"),"
              "\n    node = svg.selectAll(\".node\");"
              "\n"
              //"\nd3.json(\"graph.json\", function(error, json) {"
              //"\n  if (error) throw error;"
              "\n"
              "\nvar jsonparam = '" + strjson.toUtf8() + "';"
              "\n  root = JSON.parse(jsonparam);"
              "\n  update();"
              //"\n});"
              "\n"
              "\nfunction update() {"
              "\n  var nodes = flatten(root),"
              "\n      links = d3.layout.tree().links(nodes);"
              "\n"
              "\n  force"
              "\n      .nodes(nodes)"
              "\n      .links(links)"
              "\n      .start();"
              "\n"
              "\n  link = link.data(links, function(d) { return d.target.id; });"
              "\n"
              "\n  link.exit().remove();"
              "\n"
              "\n  link.enter().insert(\"line\", \".node\")"
              "\n      .attr(\"class\", \"link\");"
              "\n"
              "\n  node = node.data(nodes, function(d) { return d.id; });"
              "\n"
              "\n  node.exit().remove();"
              "\n"
              "\n  var nodeEnter = node.enter().append(\"g\")"
              "\n      .attr(\"class\", \"node\")"
              "\n      .on(\"click\", click)"
              "\n      .call(force.drag);"
              "\n"
              "\n  nodeEnter.append(\"circle\")"
              "\n      .attr(\"r\", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });"
              "\n"
              "\n  nodeEnter.append(\"text\")"
              "\n      .attr(\"dy\", \".35em\")"
              "\n      .text(function(d) { return d.name; });"
              "\n"
              "\n  node.select(\"circle\")"
              "\n      .style(\"fill\", color);"
              "\n}"
              "\n"
              "\nfunction tick() {"
              "\n  link.attr(\"x1\", function(d) { return d.source.x; })"
              "\n      .attr(\"y1\", function(d) { return d.source.y; })"
              "\n      .attr(\"x2\", function(d) { return d.target.x; })"
              "\n      .attr(\"y2\", function(d) { return d.target.y; });"
              "\n"
              "\n  node.attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });"
              "\n}"
              "\n"
              "\nfunction color(d) {"
              "\n  return d._children ? \"#3182bd\""
              "\n      : d.children ? \"#c6dbef\" "
              "\n      : \"#fd8d3c\"; // leaf node"
              "\n}"
              "\n"
              "\nfunction click(d) {"
              "\n  if (d3.event.defaultPrevented) return;"
              "\n  if (d.children) {"
              "\n    d._children = d.children;"
              "\n    d.children = null;"
              "\n  } else {"
              "\n    d.children = d._children;"
              "\n    d._children = null;"
              "\n  }"
              "\n  update();"
              "\n}"
              "\n"
              "\nfunction flatten(root) {"
              "\n  var nodes = [], i = 0;"
              "\n"
              "\n  function recurse(node) {"
              "\n    if (node.children) node.children.forEach(recurse);"
              "\n    if (!node.id) node.id = ++i;"
              "\n    nodes.push(node);"
              "\n  }"
              "\n"
              "\n  recurse(root);"
              "\n  return nodes;"
              "\n}"
              "\n"
              "\n</script></body></html>"
              "\n";

    QRegExp re("\\s{2,}");
    qDebug() << strHtml;

    strHtml = strHtml.replace(re,"");
    /*
    QFile file("d3onedepth.html");
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    out << strHtml;

    file.close();
*/
    m_WVD3View.setHtml(strHtml);
    //QUrl url("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/");
    //m_WVD3View.settings()->testAttribute( QWebEngineSetting::JavascriptEnabled );
    //m_WVD3View.setContent(strHtml.toUtf8(), "text/html; charset=utf-8", url);
    //m_WVD3View.setHtml(strHtml, QUrl("file:///"));
    //m_WVD3View.settings()->setObjectCacheCapacities(0,0,0);
    m_WVD3View.repaint();
    m_WVD3View.show();
}

void YMOneDepthWidget::D3ViewFile()
{
    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    /*
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";
    */
    QString strjson = "{\"name\":\" " + strCKeyword + "\",";
    strjson += ("\"children\": [");

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

    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();
        strjson += ("{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "]}";

    QString strHtml;

    strHtml = "<!DOCTYPE html>"
              "\n<meta charset=\"utf8\">"
              "\n<style>"
              "\n"
              "\n.node circle {"
              "\n  cursor: pointer;"
              "\n  stroke: #3182bd;"
              "\n  stroke-width: 1.5px;"
              "\n}"
              "\n"
              "\n.node text {"
              "\n  font: 14px sans-serif;"
              "\n  pointer-events: none;"
              "\n  text-anchor: middle;"
              "\n}"
              "\n"
              "\nline.link {"
              "\n  fill: none;"
              "\n  stroke: #9ecae1;"
              "\n  stroke-width: 1.5px;"
              "\n}"
              "\n"
              "\n</style>"
              "\n<body>"
              //"\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js\"></script>"
            "\n<script src=\"http://d3js.org/d3.v3.min.js\"></script>"
              "\n<script>"
              "\n"
              "\nvar width = 1920,"
              "\n    height = 1080,"
              "\n    root;"
              "\n"
              "\nvar force = d3.layout.force()"
              "\n    .linkDistance(80)"
              "\n    .charge(-120)"
              "\n    .gravity(.05)"
              "\n    .size([width, height])"
              "\n    .on(\"tick\", tick);"
              "\n"
              "\nvar svg = d3.select(\"body\").append(\"svg\")"
              "\n    .attr(\"width\", width)"
              "\n    .attr(\"height\", height);"
              "\n"
              "\nvar link = svg.selectAll(\".link\"),"
              "\n    node = svg.selectAll(\".node\");"
              "\n"
              //"\nd3.json(\"graph.json\", function(error, json) {"
              //"\n  if (error) throw error;"
              "\n"
              "\nvar jsonparam = '" + strjson.toUtf8() + "';"
              "\n  root = JSON.parse(jsonparam);"
              "\n  update();"
              //"\n});"
              "\n"
              "\nfunction update() {"
              "\n  var nodes = flatten(root),"
              "\n      links = d3.layout.tree().links(nodes);"
              "\n"
              "\n  force"
              "\n      .nodes(nodes)"
              "\n      .links(links)"
              "\n      .start();"
              "\n"
              "\n  link = link.data(links, function(d) { return d.target.id; });"
              "\n"
              "\n  link.exit().remove();"
              "\n"
              "\n  link.enter().insert(\"line\", \".node\")"
              "\n      .attr(\"class\", \"link\");"
              "\n"
              "\n  node = node.data(nodes, function(d) { return d.id; });"
              "\n"
              "\n  node.exit().remove();"
              "\n"
              "\n  var nodeEnter = node.enter().append(\"g\")"
              "\n      .attr(\"class\", \"node\")"
              "\n      .on(\"click\", click)"
              "\n      .call(force.drag);"
              "\n"
              "\n  nodeEnter.append(\"circle\")"
              "\n      .attr(\"r\", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });"
              "\n"
              "\n  nodeEnter.append(\"text\")"
              "\n      .attr(\"dy\", \".35em\")"
              "\n      .text(function(d) { return d.name; });"
              "\n"
              "\n  node.select(\"circle\")"
              "\n      .style(\"fill\", color);"
              "\n}"
              "\n"
              "\nfunction tick() {"
              "\n  link.attr(\"x1\", function(d) { return d.source.x; })"
              "\n      .attr(\"y1\", function(d) { return d.source.y; })"
              "\n      .attr(\"x2\", function(d) { return d.target.x; })"
              "\n      .attr(\"y2\", function(d) { return d.target.y; });"
              "\n"
              "\n  node.attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });"
              "\n}"
              "\n"
              "\nfunction color(d) {"
              "\n  return d._children ? \"#3182bd\""
              "\n      : d.children ? \"#c6dbef\" "
              "\n      : \"#fd8d3c\"; // leaf node"
              "\n}"
              "\n"
              "\nfunction click(d) {"
              "\n  if (d3.event.defaultPrevented) return;"
              "\n  if (d.children) {"
              "\n    d._children = d.children;"
              "\n    d.children = null;"
              "\n  } else {"
              "\n    d.children = d._children;"
              "\n    d._children = null;"
              "\n  }"
              "\n  update();"
              "\n}"
              "\n"
              "\nfunction flatten(root) {"
              "\n  var nodes = [], i = 0;"
              "\n"
              "\n  function recurse(node) {"
              "\n    if (node.children) node.children.forEach(recurse);"
              "\n    if (!node.id) node.id = ++i;"
              "\n    nodes.push(node);"
              "\n  }"
              "\n"
              "\n  recurse(root);"
              "\n  return nodes;"
              "\n}"
              "\n"
              "\n</script></body></html>"
              "\n";

    QRegExp re("\\s{2,}");
    qDebug() << strHtml;

    strHtml = strHtml.replace(re,"");
    QFile file("d3onedepth.html");
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    out << strHtml;
    file.close();

    QUrl url = QUrl::fromLocalFile(QDir::current().absoluteFilePath("d3onedepth.html"));

    m_WVD3View.load(url);
    //QUrl url("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/");
    //m_WVD3View.settings()->testAttribute( QWebEngineSetting::JavascriptEnabled );
    //m_WVD3View.setContent(strHtml.toUtf8(), "text/html; charset=utf-8", url);
    //m_WVD3View.setHtml(strHtml, QUrl("file:///"));
    //m_WVD3View.settings()->setObjectCacheCapacities(0,0,0);
    m_WVD3View.repaint();
    m_WVD3View.show();
}



void YMOneDepthWidget::D3ViewTree()
{
    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    /*
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";
    */
    QString strjson = "{\"name\":\" " + strCKeyword + "\",";
    strjson += ("\"children\": [");

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

    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();
        strjson += ("{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "]}";

    QString strHtml;
    strHtml = "<!DOCTYPE html>"
              "\n  <head>"
              "\n    <meta charset=\"utf8\">"
              "\n"
              "\n    <title>Tree Example</title>"
              "\n"
              "\n    <style>"
              "\n	"
              "\n	.node {"
              "\n		cursor: pointer;"
              "\n	}"
              "\n"
              "\n	.node circle {"
              "\n	  fill: #fff;"
              "\n	  stroke: steelblue;"
              "\n	  stroke-width: 2px;"
              "\n	}"
              "\n"
              "\n	.node text {"
              "\n	  font: 14px sans-serif;"
              "\n	}"
              "\n"
              "\n	.link {"
              "\n	  fill: none;"
              "\n	  stroke: #ccc;"
              "\n	  stroke-width: 2px;"
              "\n	}"
              "\n	"
              "\n    </style>"
              "\n"
              "\n  </head>"
              "\n"
              "\n  <body>"
              "\n"
              "\n<!-- load the d3.js library -->	"
              "\n<script src=\"http://d3js.org/d3.v3.min.js\"></script>"
              "\n	"
              "\n<script>"
              "\n"
              "\n"
              "\n// ************** Generate the tree diagram	 *****************"
              "\nvar margin = {top: 20, right: 120, bottom: 20, left: 120},"
              "\n	width = 1920 - margin.right - margin.left,"
              "\n	height = 1080 - margin.top - margin.bottom;"
              "\n	"
              "\nvar i = 0,"
              "\n	duration = 950,"
              "\n	root;"
              "\n"
              "\nvar tree = d3.layout.tree()"
              "\n	.size([height, width]);"
              "\n"
              "\nvar diagonal = d3.svg.diagonal()"
              "\n	.projection(function(d) { return [d.y, d.x]; });"
              "\n"
              "\nvar svg = d3.select(\"body\").append(\"svg\")"
              "\n	.attr(\"width\", width + margin.right + margin.left)"
              "\n	.attr(\"height\", height + margin.top + margin.bottom)"
              "\n  .append(\"g\")"
              "\n	.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");"
              "\n"
              "\nvar jsonparam = '" + strjson.toUtf8() + "';"
              "\n  root = JSON.parse(jsonparam);"

              "\nroot.x0 = height / 2;"
              "\nroot.y0 = 0;"
              "\n  "
              "\nupdate(root);"
              "\n"
              "\nd3.select(self.frameElement).style(\"height\", \"500px\");"
              "\n"
              "\nfunction update(source) {"
              "\n"
              "\n  // Compute the new tree layout."
              "\n  var nodes = tree.nodes(root).reverse(),"
              "\n	  links = tree.links(nodes);"
              "\n"
              "\n  // Normalize for fixed-depth."
              "\n  nodes.forEach(function(d) { d.y = d.depth * 180; });"
              "\n"
              "\n  var node = svg.selectAll(\"g.node\")"
              "\n	  .data(nodes, function(d) { return d.id || (d.id = ++i); });"
              "\n"
              "\n  // Enter any new nodes at the parent's previous position."
              "\n  var nodeEnter = node.enter().append(\"g\")"
              "\n	  .attr(\"class\", \"node\")"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + source.y0 + \",\" + source.x0 + \")\"; })"
              "\n	  .on(\"click\", click);"
              "\n"
              "\n  nodeEnter.append(\"circle\")"
              "\n	  .attr(\"r\", 1e-6)"
              "\n	  .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; });"
              "\n"
              "\n  nodeEnter.append(\"text\")"
              "\n	  .attr(\"x\", function(d) { return d.children || d._children ? -13 : 13; })"
              "\n	  .attr(\"dy\", \".35em\")"
              "\n	  .attr(\"text-anchor\", function(d) { return d.children || d._children ? \"end\" : \"start\"; })"
              "\n	  .text(function(d) { return d.name; })"
              "\n	  .style(\"fill-opacity\", 1e-6);"
              "\n"
              "\n  // Transition nodes to their new position."
              "\n  var nodeUpdate = node.transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + d.y + \",\" + d.x + \")\"; });"
              "\n"
              "\n  nodeUpdate.select(\"circle\")"
              "\n	  .attr(\"r\", 10)"
              "\n	  .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; });"
              "\n"
              "\n  nodeUpdate.select(\"text\")"
              "\n	  .style(\"fill-opacity\", 1);"
              "\n"
              "\n  // Transition exiting nodes to the parent's new position."
              "\n  var nodeExit = node.exit().transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + source.y + \",\" + source.x + \")\"; })"
              "\n	  .remove();"
              "\n"
              "\n  nodeExit.select(\"circle\")"
              "\n	  .attr(\"r\", 1e-6);"
              "\n"
              "\n  nodeExit.select(\"text\")"
              "\n	  .style(\"fill-opacity\", 1e-6);"
              "\n"
              "\n  var link = svg.selectAll(\"path.link\")"
              "\n	  .data(links, function(d) { return d.target.id; });"
              "\n"
              "\n  // Enter any new links at the parent's previous position."
              "\n  link.enter().insert(\"path\", \"g\")"
              "\n	  .attr(\"class\", \"link\")"
              "\n	  .attr(\"d\", function(d) {"
              "\n		var o = {x: source.x0, y: source.y0};"
              "\n		return diagonal({source: o, target: o});"
              "\n	  });"
              "\n"
              "\n  // Transition links to their new position."
              "\n  link.transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"d\", diagonal);"
              "\n"
              "\n  // Transition exiting nodes to the parent's new position."
              "\n  link.exit().transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"d\", function(d) {"
              "\n		var o = {x: source.x, y: source.y};"
              "\n		return diagonal({source: o, target: o});"
              "\n	  })"
              "\n	  .remove();"
              "\n"
              "\n  // Stash the old positions for transition."
              "\n  nodes.forEach(function(d) {"
              "\n	d.x0 = d.x;"
              "\n	d.y0 = d.y;"
              "\n  });"
              "\n}"
              "\n"
              "\n// Toggle children on click."
              "\nfunction click(d) {"
              "\n  if (d.children) {"
              "\n	d._children = d.children;"
              "\n	d.children = null;"
              "\n  } else {"
              "\n	d.children = d._children;"
              "\n	d._children = null;"
              "\n  }"
              "\n  update(d);"
              "\n}"
              "\n"
              "\n</script>"
              "\n	"
              "\n  </body>"
              "\n</html>";

    qDebug() << strHtml;
    /*
    QFile file("d3onedepthtree.html");
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    out << strHtml;

    file.close();
    */
    m_WVD3View.setHtml(strHtml);
    //m_WVD3View.settings()->setObjectCacheCapacities(0,0,0);
    m_WVD3View.repaint();
    m_WVD3View.show();
}



void YMOneDepthWidget::D3ViewTreeFile()
{
    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    /*
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";
    */
    QString strjson = "{\"name\":\" " + strCKeyword + "\",";
    strjson += ("\"children\": [");

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

    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();
        strjson += ("{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "]}";

    QString strHtml;
    strHtml = "<!DOCTYPE html>"
              "\n  <head>"
              "\n    <meta charset=\"utf8\">"
              "\n"
              "\n    <title>Tree Example</title>"
              "\n"
              "\n    <style>"
              "\n	"
              "\n	.node {"
              "\n		cursor: pointer;"
              "\n	}"
              "\n"
              "\n	.node circle {"
              "\n	  fill: #fff;"
              "\n	  stroke: steelblue;"
              "\n	  stroke-width: 2px;"
              "\n	}"
              "\n"
              "\n	.node text {"
              "\n	  font: 14px sans-serif;"
              "\n	}"
              "\n"
              "\n	.link {"
              "\n	  fill: none;"
              "\n	  stroke: #ccc;"
              "\n	  stroke-width: 2px;"
              "\n	}"
              "\n	"
              "\n    </style>"
              "\n"
              "\n  </head>"
              "\n"
              "\n  <body>"
              "\n"
              "\n<!-- load the d3.js library -->	"
              "\n<script src=\"http://d3js.org/d3.v3.min.js\"></script>"
              "\n	"
              "\n<script>"
              "\n"
              "\n"
              "\n// ************** Generate the tree diagram	 *****************"
              "\nvar margin = {top: 20, right: 120, bottom: 20, left: 120},"
              "\n	width = 1920 - margin.right - margin.left,"
              "\n	height = 1080 - margin.top - margin.bottom;"
              "\n	"
              "\nvar i = 0,"
              "\n	duration = 950,"
              "\n	root;"
              "\n"
              "\nvar tree = d3.layout.tree()"
              "\n	.size([height, width]);"
              "\n"
              "\nvar diagonal = d3.svg.diagonal()"
              "\n	.projection(function(d) { return [d.y, d.x]; });"
              "\n"
              "\nvar svg = d3.select(\"body\").append(\"svg\")"
              "\n	.attr(\"width\", width + margin.right + margin.left)"
              "\n	.attr(\"height\", height + margin.top + margin.bottom)"
              "\n  .append(\"g\")"
              "\n	.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");"
              "\n"
              "\nvar jsonparam = '" + strjson.toUtf8() + "';"
              "\n  root = JSON.parse(jsonparam);"

              "\nroot.x0 = height / 2;"
              "\nroot.y0 = 0;"
              "\n  "
              "\nupdate(root);"
              "\n"
              "\nd3.select(self.frameElement).style(\"height\", \"500px\");"
              "\n"
              "\nfunction update(source) {"
              "\n"
              "\n  // Compute the new tree layout."
              "\n  var nodes = tree.nodes(root).reverse(),"
              "\n	  links = tree.links(nodes);"
              "\n"
              "\n  // Normalize for fixed-depth."
              "\n  nodes.forEach(function(d) { d.y = d.depth * 180; });"
              "\n"
              "\n  var node = svg.selectAll(\"g.node\")"
              "\n	  .data(nodes, function(d) { return d.id || (d.id = ++i); });"
              "\n"
              "\n  // Enter any new nodes at the parent's previous position."
              "\n  var nodeEnter = node.enter().append(\"g\")"
              "\n	  .attr(\"class\", \"node\")"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + source.y0 + \",\" + source.x0 + \")\"; })"
              "\n	  .on(\"click\", click);"
              "\n"
              "\n  nodeEnter.append(\"circle\")"
              "\n	  .attr(\"r\", 1e-6)"
              "\n	  .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; });"
              "\n"
              "\n  nodeEnter.append(\"text\")"
              "\n	  .attr(\"x\", function(d) { return d.children || d._children ? -13 : 13; })"
              "\n	  .attr(\"dy\", \".35em\")"
              "\n	  .attr(\"text-anchor\", function(d) { return d.children || d._children ? \"end\" : \"start\"; })"
              "\n	  .text(function(d) { return d.name; })"
              "\n	  .style(\"fill-opacity\", 1e-6);"
              "\n"
              "\n  // Transition nodes to their new position."
              "\n  var nodeUpdate = node.transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + d.y + \",\" + d.x + \")\"; });"
              "\n"
              "\n  nodeUpdate.select(\"circle\")"
              "\n	  .attr(\"r\", 10)"
              "\n	  .style(\"fill\", function(d) { return d._children ? \"lightsteelblue\" : \"#fff\"; });"
              "\n"
              "\n  nodeUpdate.select(\"text\")"
              "\n	  .style(\"fill-opacity\", 1);"
              "\n"
              "\n  // Transition exiting nodes to the parent's new position."
              "\n  var nodeExit = node.exit().transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"transform\", function(d) { return \"translate(\" + source.y + \",\" + source.x + \")\"; })"
              "\n	  .remove();"
              "\n"
              "\n  nodeExit.select(\"circle\")"
              "\n	  .attr(\"r\", 1e-6);"
              "\n"
              "\n  nodeExit.select(\"text\")"
              "\n	  .style(\"fill-opacity\", 1e-6);"
              "\n"
              "\n  var link = svg.selectAll(\"path.link\")"
              "\n	  .data(links, function(d) { return d.target.id; });"
              "\n"
              "\n  // Enter any new links at the parent's previous position."
              "\n  link.enter().insert(\"path\", \"g\")"
              "\n	  .attr(\"class\", \"link\")"
              "\n	  .attr(\"d\", function(d) {"
              "\n		var o = {x: source.x0, y: source.y0};"
              "\n		return diagonal({source: o, target: o});"
              "\n	  });"
              "\n"
              "\n  // Transition links to their new position."
              "\n  link.transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"d\", diagonal);"
              "\n"
              "\n  // Transition exiting nodes to the parent's new position."
              "\n  link.exit().transition()"
              "\n	  .duration(duration)"
              "\n	  .attr(\"d\", function(d) {"
              "\n		var o = {x: source.x, y: source.y};"
              "\n		return diagonal({source: o, target: o});"
              "\n	  })"
              "\n	  .remove();"
              "\n"
              "\n  // Stash the old positions for transition."
              "\n  nodes.forEach(function(d) {"
              "\n	d.x0 = d.x;"
              "\n	d.y0 = d.y;"
              "\n  });"
              "\n}"
              "\n"
              "\n// Toggle children on click."
              "\nfunction click(d) {"
              "\n  if (d.children) {"
              "\n	d._children = d.children;"
              "\n	d.children = null;"
              "\n  } else {"
              "\n	d.children = d._children;"
              "\n	d._children = null;"
              "\n  }"
              "\n  update(d);"
              "\n}"
              "\n"
              "\n</script>"
              "\n	"
              "\n  </body>"
              "\n</html>";

    qDebug() << strHtml;

    QFile file("d3onedepthtree.html");
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);

    out << strHtml;

    file.close();
    QUrl url = QUrl::fromLocalFile(QDir::current().absoluteFilePath("d3onedepthtree.html"));

    m_WVD3View.load(url);
    //m_WVD3View.setHtml(strHtml);
    //m_WVD3View.settings()->setObjectCacheCapacities(0,0,0);
    m_WVD3View.repaint();
    m_WVD3View.show();
}

QString YMOneDepthWidget::Json()
{

    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";

    return strjson;

}

bool YMOneDepthWidget::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 YMOneDepthWidget::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();
}



YMOneDepthWidget::~YMOneDepthWidget()
{

}

void YMOneDepthWidget::clearViewResult()
{

}



void YMOneDepthWidget::clearView()
{
    m_mapViewResult.clear();
    m_mapViewResult2.clear();
}
void YMOneDepthWidget::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();
        }
    }
    {
        QString extractor = json.Get(strJson, "Extractor");
        m_pleFilterExtractor->setText(extractor);
    }
    {
        QString keywordfilter = json.Get(strJson, "KeywordFilter");
        m_pleFilterKeyword->setText(keywordfilter);
    }
    {
        QString keywordlengthfilter = json.Get(strJson, "KeywordLengthFilter");
        m_pleFilterKeywordLength->setText(keywordlengthfilter);
    }
    {
        QString RankFilterAll = json.Get(strJson, "RankFilterAll");
        m_pleFilterRankALL->setText(RankFilterAll);
    }
    {
        QString RankSeparated = json.Get(strJson, "RankFilterSeparated");
        m_pleFilterRankSeparated->setText(RankSeparated);
    }
    {
        QString CenterKeyword = json.Get(strJson, "CenterKeyword");
        m_pleCKeyword->setText(CenterKeyword);
    }

}



void YMOneDepthWidget::SortViewResult()
{
    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 YMOneDepthWidget::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++)
        {

            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,QMap<int,QMap<QString, QString> > >::iterator iterPosi = m_mapViewResult2.begin();
    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++, iterPosi++)
    {
        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;
        }

        {
            int ncRow = 0;

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

            QMapIterator<int, QMap<QString,QString>> j(m_mapViewResult2[iterPosi.key()]);
            j.toBack();
            while(j.hasPrevious())
            {
                j.previous();
                for(QMap<QString, QString>::iterator iterPosii = m_mapViewResult2[iterPosi.key()][j.key()].begin(); iterPosii != m_mapViewResult2[iterPosi.key()][j.key()].end(); iterPosii++)
                {
                    pNew->setItem(ncRow,0,new QTableWidgetItem(QString(iterPosii.key())));
                    pNew->setItem(ncRow,1,new QTableWidgetItem(QString(iterPosii.value())));
                    pNew->setItem(ncRow,2,new QTableWidgetItem(QString::number(j.key())));
                    ncRow++;
                }
            }
            temp->addTab(pNew, "ALL");
            m_lTable << pNew;
        }

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

void YMOneDepthWidget::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();
}

void YMOneDepthWidget::SaveFileSimple()
{
    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();
    out << strCKeyword;

    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 << "," << strKeyword;
        }

    }
    out << endl;
    file.close();
}

QMap<QString, int> YMOneDepthWidget::getResult()
{
    return m_mapResult;
}



void YMOneDepthWidget::TestUpload()
{
    //QMap<QString, int> mapResult = m_mapResult;

    QString strCKeyword = getCenterKeyword();
    //qDebug() << "executed";
    QString strjson = "{\n\t\"name\":\" " + strCKeyword + "\",\n";
    strjson += ("\t\"children\": [\n");

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

    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();
        strjson += ("\t{\"name\": \"" + strKeyword + "\", \"size\": " + QString::number(nCount) + "},\n");
    }
    strjson = strjson.trimmed();
    strjson = strjson.left(strjson.length() - 1);
    strjson += "\n\t]\n}";

    /*
    QFile file("c:/data/jsontest.txt");
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;
    QTextStream out(&file);

    out << strjson;

    file.close();
    */


/*
    QSqlDatabase dbWeb = QSqlDatabase::addDatabase("QMYSQL");
    dbWeb.setHostName("db.big-bird.co.kr");
    dbWeb.setUserName("concepters");
    dbWeb.setPassword("con97996655");
    dbWeb.setDatabaseName("dbconcepters");

    int nCompany = 90;

    if(!dbWeb.open())
        qDebug() << "DB open Failed";



    QSqlQuery query(QSqlDatabase::database(dbWeb.connectionName()));

    QString strquery;

    strquery = "insert into stats_json (jdata, company_num) values ('" + strjson + "', " + QString::number(nCompany) + ")";

    if(!query.exec(strquery.toUtf8()))
    {
        strquery = "update stats_json set jdata='" + strjson + "' where company_num=" + QString::number(nCompany);
        if(!query.exec(strquery.toUtf8()))
        {
            qDebug() << query.lastError().text();
        }
    }


    dbWeb.close();
*/

}

QString YMOneDepthWidget::getCenterKeyword()
{
    return m_pleCKeyword->text().trimmed();
}

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

    {
        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("CenterKeyword", getCenterKeyword());
    }

    {
        mapParam.insert("CountMethod", m_pcbCountMethod->currentText().trimmed());
    }

    {
        if(!m_pleFilterExtractor->text().trimmed().isEmpty())
            mapParam.insert("Extractor", m_pleFilterExtractor->text().trimmed());
    }
    {
        if(!m_pleFilterKeyword->text().trimmed().isEmpty())
            mapParam.insert("KeywordFilter",m_pleFilterKeyword->text().trimmed());
    }
    {
        if(!m_pleFilterKeywordLength->text().trimmed().isEmpty())
            mapParam.insert("KeywordLengthFilter", m_pleFilterKeywordLength->text().trimmed());
    }
    qDebug() << m_pleFilterKeyword->text().trimmed();
    {
        if(!m_pleFilterRankALL->text().trimmed().isEmpty())
            mapParam.insert("RankFilterAll", m_pleFilterRankALL->text().trimmed());
    }
    {
        if(!m_pleFilterRankSeparated->text().trimmed().isEmpty())
            mapParam.insert("RankFilterSeparated", m_pleFilterRankSeparated->text().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;
}
