#include "droptablewidget.h"

//Original dn'd from here: http://www.qtcentre.org/threads/17536-Drag-and-Drop-QTableWidget-in-UI-file
//This constructor also initialize c++ constants (http://stackoverflow.com/questions/1423696/how-to-initialize-a-const-field-in-constructor)

DropTableWidget::DropTableWidget(QWidget *parent, QBrush _disabledBackStyle,
                                 QBrush _disabledTextStyle) : QTableWidget(parent),
    disabledBackStyle(_disabledBackStyle),
    disabledTextStyle(_disabledTextStyle){

    //set widget default properties:
    //    setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);
    //    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setDragDropMode(QAbstractItemView::DropOnly);
    setAlternatingRowColors(true);
    //    setSelectionMode(QAbstractItemView::NoSelection);
    //    setShowGrid(false);
    //    setWordWrap(false);
    setAcceptDrops(true);

    //Custom added for Vago
    setColumnCount(3);

    //set Header of tables
    setHorizontalHeaderLabels(QStringList()<<"File/Folder"<<"From/To"<<"Command");
    horizontalHeader()->setStretchLastSection(true);
}

void DropTableWidget::dragEnterEvent(QDragEnterEvent *event) {
    event->acceptProposedAction();
    emit changed(event->mimeData());
}

void DropTableWidget::dragMoveEvent(QDragMoveEvent *event) {
    event->acceptProposedAction();
}

void DropTableWidget::dropEvent(QDropEvent *event) {

    const QMimeData* mimeData = event->mimeData();

    event->acceptProposedAction();

    QStringList pathList = QStringList();

    // check for our needed mime type, here a file or a list of files
    if (mimeData->hasUrls())
    {
        QList<QUrl> urlList = mimeData->urls();

        // extract the local paths of the files
        for (int i = 0; i < urlList.size() && i < 2048; ++i)
        {
            pathList.append(urlList.at(i).toLocalFile());
        }
    }

    emit dropped(this, pathList);
}

void DropTableWidget::dragLeaveEvent(QDragLeaveEvent *event) {
    event->accept();
}

void DropTableWidget::clear() {
    emit changed();
}

//Context menu actions
void DropTableWidget::contextMenuEvent(QContextMenuEvent *event){
    //All the context menu is processed at the mainwindow class
    emit dtContextMenu(this,event);
}

//Custom function to swap items positions in the table
void DropTableWidget::swapPositions(QList<int> rowsSelected, int numUnitsToMove){
    QList<tableRowProperties> orderedList = QList<tableRowProperties>();

    //Make a copy of the actual list to swap
    for(int i=0; i<this->rowCount(); i++){
        orderedList.append(tableRowProperties()); //Add each row property (initialize)
        for(int j=0; j<this->columnCount(); j++){
            orderedList[i].cells.append(this->item(i,j)->text());

            if(this->item(i,j)->background()==this->disabledBackStyle){ //Is it disabled?
                orderedList[i].isDisabled=true;
            }

        }
    }

    //Swap the copied list for each item
    if(numUnitsToMove<0){ //if going up we need to start from the first item
        for(int i=0; i<rowsSelected.size(); i++){
            orderedList.swap(rowsSelected.at(i),rowsSelected.at(i)+numUnitsToMove);
        }
    }
    else{ //if going down we need to start from the last item
        for(int i=rowsSelected.size()-1; i>=0; i--){
            orderedList.swap(rowsSelected.at(i),rowsSelected.at(i)+numUnitsToMove);
        }
    }

    this->clear(); //clear previous selections

    //Switch with the ordered one
    for(int i=0; i<this->rowCount(); i++){
        for(int j=0; j<this->columnCount(); j++){
            QTableWidgetItem *orderedItem = new QTableWidgetItem(orderedList[i].cells.at(j));
            this->setItem(i,j,orderedItem);

            if(orderedList[i].isDisabled){ //Restored disabled style
                setDisableStyleWidgetItem(orderedItem);
            }
        }
        this->updateTableToolTips(i);
    }

    this->clearSelection(); //clear previous selections

    //Select the moved rows
    this->setRangeSelected(QTableWidgetSelectionRange(rowsSelected.at(0)+numUnitsToMove,this->columnCount()-1,rowsSelected.at(rowsSelected.size()-1)+numUnitsToMove,0),true);
    //Top > top row number, Left > num colums to select to left, Bottom > bottom row number, Right > start at each column (from right)
}

//Reset a item to its initial style
void DropTableWidget::resetStyleWidgetItem(QTableWidgetItem *currentItem){
    if((currentItem->row()+1)%2==0){ //if the row number is par it use the alternate color scheme
        currentItem->setBackground(QPalette().brush(QPalette::Normal,QPalette::AlternateBase));
    }
    else{
        currentItem->setBackground(QPalette().brush(QPalette::Normal,QPalette::Base));
    }
    currentItem->setForeground(QPalette().brush(QPalette::Normal,QPalette::WindowText));
}

//Disable a table widget item
void DropTableWidget::setDisableStyleWidgetItem(QTableWidgetItem *currentItem){
    currentItem->setBackground(this->disabledBackStyle);
    currentItem->setForeground(this->disabledTextStyle);
}

QString DropTableWidget::getFileAbsolute(int row){
    QString fileCommand=this->item(row,2)->text();

    int idxFileName=fileCommand.indexOf(this->item(row,0)->text()); //Search first for the file name

    int fileAbsoluteStartIdx=fileCommand.lastIndexOf("\"",idxFileName);

    fileCommand.remove(0,fileAbsoluteStartIdx);

    int fileAbsoluteEndIdx=fileCommand.indexOf('"',1); //1 to find the end quote and not the start

    return fileCommand.remove(fileAbsoluteEndIdx+1,(fileCommand.size()-1)-fileAbsoluteEndIdx);
}

QString DropTableWidget::getOutputAbsolute(int row){
    QString command=this->item(row,2)->text();

    int fileAbsoluteEndIdx=command.indexOf("/\"",0); //let's find the /" (end of path)

    command.remove(fileAbsoluteEndIdx,command.size()-1);

    int fileAbsoluteStartIdx=command.lastIndexOf("\"",command.size()-1)+1;

    return command.remove(0,fileAbsoluteStartIdx);
}


void DropTableWidget::updateTableToolTips(int row){
    for(int i=0; i<this->columnCount(); i++){
        this->item(row,i)->setToolTip(this->item(row,i)->text());
    }
}

