#include "gitmergedialog.h"
#include "ui_gitmergedialog.h"
#include "gitmanager.h"
#include "../widgets/infomessagebox.h"

GitMergeDialog::GitMergeDialog(const QString& folder, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GitMergeDialog)
{
    ui->setupUi(this);
    mManager = new GitManager();
    mCurrentBranchIndex=-1;
    QStringList branches =mManager->listBranches(mFolder,mCurrentBranchIndex);
    ui->cbBranch->addItems(branches);
    ui->cbBranch->setCurrentIndex(mCurrentBranchIndex);
    ui->btnOk->setEnabled(false);
    ui->rbBranch->setChecked(true);
    ui->txtMergeMessage->setPlainText(QObject::tr("<Auto Generated by Git>"));
    mFolder = mManager->rootFolder(folder);
    if (branches.isEmpty()) {
        QString currentBranch;
        if (mManager->hasRepository(folder,currentBranch)) {
            ui->cbBranch->addItem(currentBranch);
            ui->btnOk->setEnabled(false);
        }
        ui->grpOptions->setEnabled(false);
        ui->txtMergeMessage->setEnabled(false);
    }
}

GitMergeDialog::~GitMergeDialog()
{
    delete mManager;
    delete ui;
}

void GitMergeDialog::on_btnCancel_clicked()
{
    reject();
}

void GitMergeDialog::closeEvent(QCloseEvent */* event */)
{
    reject();
}


void GitMergeDialog::on_btnOk_clicked()
{
    QString output;
    if (mManager->merge(mFolder,ui->cbBranch->currentText(),
                    ui->chkSquash->isChecked(),
                    ui->chkFastForwardOnly->isChecked(),
                    ui->chkNoFastFoward->isChecked(),
                    ui->chkNoCommit->isChecked(),
                    output,
                    ui->txtMergeMessage->toPlainText()
                        )) {
        InfoMessageBox box;
        box.setMessage(output);
        box.exec();
        accept();
    } else {
        InfoMessageBox box;
        box.setMessage(output);
        box.exec();
        reject();
    }
}


void GitMergeDialog::on_cbBranch_currentIndexChanged(int index)
{
    ui->btnOk->setEnabled(mCurrentBranchIndex!=index);
}