#include "stable.h"
#include <QKeyEvent>
#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QHeaderView>
#include <QMessageBox>

STable::STable(QWidget *parent):
    QTableWidget(parent)
{
    setSortingEnabled(true);
    verticalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(verticalHeader(),SIGNAL(customContextMenuRequested(QPoint)),SLOT(HeaderContextMenuShow(QPoint)));
    connect(this,SIGNAL(cellClicked(int,int)),SLOT(CellClick(int,int)));
    setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    m_nArticle = E_ARTICLE_NONE;
}

void STable::SetHeaderList(QVector <QStringList>* _pvecHead,int _nColumn)
{
    setColumnCount(_pvecHead->size());
    int i = 0;
    foreach(QStringList strList, *_pvecHead )
        setHorizontalHeaderItem(i++,new QTableWidgetItem(strList.at(_nColumn)));
}

void STable::SetHeaderList(QStringList _Head)
{
    setColumnCount(_Head.size());
    int i = 0;
    foreach(QString str,_Head )
        setHorizontalHeaderItem(i++,new QTableWidgetItem(str));
}


void STable::keyPressEvent(QKeyEvent* event)
{
    // If Ctrl-C typed    
    if (event->key() == Qt::Key_C && (event->modifiers() & Qt::ControlModifier))
        Copy();
    if (event->key() == Qt::Key_V && (event->modifiers() & Qt::ControlModifier))
        Paste();
    if (event->key() == Qt::Key_Delete)
        Delete();
}

void STable::menuInsert()
{
    int nRow = currentRow();
    insertRow(nRow);
    for (int i = 0; i < columnCount() ; i++)
        setItem(nRow,i,new QTableWidgetItem(" "));
}


void STable::menuDelete()
{
    int nCount = 0;
    foreach(QModelIndex current,verticalHeader()->selectionModel()->selectedRows())
    {
        removeRow(current.row()-nCount);
        nCount++;
    }
}

void STable::HeaderContextMenuShow(const QPoint& pos) // this is a slot
{
    QMenu myMenu;
    myMenu.addAction("Insert", this, SLOT(menuInsert()));
    myMenu.addAction("Delete", this, SLOT(menuDelete()));
    myMenu.exec(mapToGlobal(pos));
}

void STable::CellClick(int nRow,int nPrev)
{
    Q_UNUSED(nPrev);
    if (rowHeight(nRow) == 30)
        resizeRowToContents(nRow);
    else
        setRowHeight(nRow,30);
    repaint();
}

void STable::Copy()
{
    QModelIndexList cells = selectedIndexes();
    //qSort(cells);
    QString text;
    int currentRow = 0;
    foreach (const QModelIndex& cell, cells)
    {
        if (text.length() == 0)
        {
        }
        else if (cell.row() != currentRow)
            text += '\n';
        else
            text += '\t';
        currentRow = cell.row();
        text += cell.data().toString();
    }
    QApplication::clipboard()->setText(text);
}

void STable::Paste()
{
    //if(qApp->clipboard()->mimeData()->hasHtml())
    {
        // TODO, parse the html data
    }
    //else
    {
        QModelIndexList cells = selectedIndexes();
        qSort(cells);
        if (cells.size() == 0) return;

        QString str = QApplication::clipboard()->text();
        QStringList strRows = str.split("\n");
        if (strRows.size() == 0) return;

        int nStartRow = cells.at(0).row();
        int nStartCol = cells.at(0).column();
        int nRows = strRows.size();
        {
            int nPlusRow = nStartRow + nRows - rowCount();
            if (nPlusRow > 0)
            {
                int rowcnt = rowCount();
                setRowCount(rowCount()+nPlusRow);
                for(int i = rowcnt; i < rowcnt + nPlusRow; i++)
                {
                    for(int j = 0; j < columnCount(); j++)
                    {
                        setItem(i, j, new QTableWidgetItem(QString("  ")));
                    }
                }
            }
        }
        int nRow = nStartRow;
        foreach(QString strRow,strRows)
        {
            QStringList strCols = strRow.split("\t");
            int nCol = nStartCol;
            foreach(QString strCol,strCols)
            {
                if (nCol >= columnCount()) continue;
                QTableWidgetItem *pItem;
                if (nRows >= nRows)
                    pItem = new QTableWidgetItem;
                else
                    pItem = item(nRow,nCol);
                pItem->setText(" "+strCol.trimmed()+" ");
                setItem(nRow,nCol,pItem);
                nCol++;
            }
            nRow++;
        }
    }
}

void STable::Delete()
{
    QModelIndexList cells = selectedIndexes();
    foreach (const QModelIndex& cell, cells)
    {
        QTableWidgetItem *pItem = item(cell.row(),cell.column());
        if (pItem != NULL)
        {
            pItem->setText("");
            setItem(cell.row(),cell.column(),pItem);
        }
    }
}

void STable::setArticleSelect(int _nArticle)
{
    m_nArticle = _nArticle;
}

QString STable::GetArticleType(int _nSelect)
{
    switch(_nSelect)
    {
    case E_ARTICLE_NONE:
        return QString("{None} ");
    case E_ARTICLE_BODY:
        return QString("{Body} ");
    case E_ARTICLE_REPLY:
        return QString("{Relpy} ");
    case E_ARTICLE_ALL:
        return QString("{All} ");
    }
    return QString("{Other} ");
}
