#include "manualcommands.h"
#include "ui_manualcommands.h"

ManualCommands::ManualCommands(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ManualCommands)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_DeleteOnClose, true); //destroy itself once finished.
    this->myProcess = new QProcess();
    this->myProcess->setProcessChannelMode(QProcess::MergedChannels);
    this->myProcess->setWorkingDirectory(UtilVago::getAppPath());
    ui->leManualCommand->installEventFilter(this);

    this->nextInsertHistoryIdx=0;
    this->searchHistoryIdx=0;
    for(int i=0; i<this->limHistory; i++){
        this->history[i]=""; //clean array
    }
}

ManualCommands::~ManualCommands()
{
    delete myProcess;
    delete ui;
}

void ManualCommands::on_pbInput_clicked()
{
    executeCommand();
}

void ManualCommands::executeCommand(){

    QString toolExecutable;

    if(ui->cbTargetTool->currentText() == "OniSplit"){
        toolExecutable = UtilVago::getOniSplitExecutable();
    }
    else{
        toolExecutable = UtilVago::getXmlToolsExecutable();
    }

    QString command=ui->leManualCommand->text().trimmed();

    if(command.isEmpty()){
        Util::Dialogs::showError("Please input a command first.");
        return;
    }

    //Only add to the history if the last command is different
    bool different=false;
    if(this->nextInsertHistoryIdx==0){ //at the limit
        if(this->history[this->limHistory-1]!=command){
            different=true;
        }
    }
    else{
        if(this->history[this->nextInsertHistoryIdx-1]!=command){
            different=true;
        }
    }

    if(different){
        this->history[this->nextInsertHistoryIdx++]=command; //assign and increment

        if(this->nextInsertHistoryIdx==this->limHistory){ //if we are at the limit begin override
            this->nextInsertHistoryIdx=0;
        }
    }

    this->myProcess->start(toolExecutable+" "+ui->leManualCommand->text());
    this->myProcess->waitForFinished(120000); //wait 2 minutes at maximum
    ui->ptOutput->appendPlainText("> " + ui->cbTargetTool->currentText() + " " + command);
    ui->ptOutput->appendPlainText(this->myProcess->readAll());
    ui->ptOutput->ensureCursorVisible();
    ui->ptOutput->verticalScrollBar()->setValue( ui->ptOutput->verticalScrollBar()->maximum() );
    ui->leManualCommand->clear();
}

void ManualCommands::on_pcCopyClipboard_clicked()
{
    QApplication::clipboard()->setText(ui->ptOutput->toPlainText());
}

void ManualCommands::on_pbClear_clicked()
{
    if(Util::Dialogs::showQuestion(this,"Clear the output?")){
        ui->ptOutput->clear();
    }
}

//Allows detecting arrows press for history without subclassing lineedit.
bool ManualCommands::eventFilter(QObject* obj, QEvent *event)
{
    if (obj == ui->leManualCommand)
    {
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->key() == Qt::Key_Up) //UP ARROW
            {

                int oldValue=this->searchHistoryIdx;

                //if it isn't the first member of history continue decrementing
                if(this->searchHistoryIdx!=this->nextInsertHistoryIdx){ //for when it didn't the round
                    this->searchHistoryIdx--;
                }

                //start with the last elemented inputted
                if(ui->leManualCommand->text().trimmed().isEmpty()){
                    this->searchHistoryIdx=this->nextInsertHistoryIdx-1;
                }

                //rotate
                if(this->searchHistoryIdx < 0){
                    this->searchHistoryIdx=this->limHistory-1; //start from behind (49)
                }
                else if(this->searchHistoryIdx == this->limHistory){
                    this->searchHistoryIdx=0; //start from 0 again
                }

                //not filled yet value? Stop.
                if(this->history[this->searchHistoryIdx].isEmpty()){
                    this->searchHistoryIdx=oldValue;
                    return true;
                }

                ui->leManualCommand->setText(this->history[this->searchHistoryIdx]);

                return true;

            }
            else if(keyEvent->key() == Qt::Key_Down) //DOWN ARROW
            {
                if(ui->leManualCommand->text().trimmed().isEmpty()){
                    return true;
                }

                int oldValue=this->searchHistoryIdx;

                //Continue incrementing if it isnt the last member of history
                if(this->searchHistoryIdx!=this->nextInsertHistoryIdx-1 && //for when it didn't the round
                        !(this->nextInsertHistoryIdx==0 && this->searchHistoryIdx==this->limHistory-1)){ //for when it did the round
                    this->searchHistoryIdx++;
                }

                //rotate
                if(this->searchHistoryIdx < 0){
                    this->searchHistoryIdx=this->limHistory-1; //start from behind (49)
                }
                else if(this->searchHistoryIdx == this->limHistory){
                    this->searchHistoryIdx=0; //start from 0 again
                }

                //not filled yet value? Stop.
                if(this->history[this->searchHistoryIdx].isEmpty()){
                    this->searchHistoryIdx=oldValue;
                    return true;
                }

                ui->leManualCommand->setText(this->history[this->searchHistoryIdx]);

                return true;
            }
        }
        return false;
    }
    return QMainWindow::eventFilter(obj, event);
}
