#include <QtGui>
#include <qmessagebox.h>

#include "rundlg.h"

#include "simgrid_simulation.h"
#include "templates.h"


RunDlg::RunDlg(QWidget *widget)
    : QDialog(widget)
{
    ui.setupUi(this);

	SimulationTemplates temps;

	ui.runButton->setEnabled(temps.fill(ui.templateCombo, temps.lastTemplateRun()) != 0);

	connect(ui.runButton, SIGNAL(clicked()), this, SLOT(run()));
	connect(ui.fileButton, SIGNAL(clicked()), this, SLOT(fileOpen()));
	connect(ui.templateCombo, SIGNAL(activated(int)), this, SLOT(templateChanged(int)));

	templateChanged(ui.templateCombo->currentIndex());
}

void RunDlg::templateChanged(int idx)
{
	QString tempEntry = ui.templateCombo->itemData(idx).toString();
	if(!tempEntry.isEmpty()) {
		SimulationTemplates temps;
		ui.deployFileEdit->setText(temps.lastDeployFile(tempEntry));
	}
}

void RunDlg::run()
{
	int idx = ui.templateCombo->currentIndex();
	if(idx == -1) {
		QMessageBox::critical(this, tr("Run Simulation"), tr("No template selected."));
		reject();
		return;
	}

	if(!ui.deployFileEdit->text().isEmpty() && !QFile::exists(ui.deployFileEdit->text())) {
		QMessageBox::critical(this, tr("Run Simulation"), tr("Deployment file not found."));
							  ui.deployFileEdit->setFocus(Qt::OtherFocusReason);
		reject();
		return;
	}

	SimulationTemplates temps;
	_tempEntry = ui.templateCombo->itemData(idx).toString();

	_scriptFile = temps.scriptFile(_tempEntry);
	_deployFile = ui.deployFileEdit->text();

	temps.setLastDeployFile(_tempEntry, _deployFile);
	temps.setLastTemplateRun(_tempEntry);

	accept();
}

void RunDlg::fileOpen()
{
	QFileDialog fileDlg(this, tr("Select Deployment File"));
	QString dirName;
	QDir dir;

	SimulationTemplates temps;

	dirName = temps.lastDeployDir();

	dir.setPath(dirName);
	if(!dir.exists()) {
		dir = QDir::home();
	}

	fileDlg.setFileMode(QFileDialog::ExistingFile);
	fileDlg.setDirectory(dir);
	fileDlg.setFilter(tr("All Deploy files (*.xml)"));

	if(fileDlg.exec() == QDialog::Accepted) {
		QStringList files = fileDlg.selectedFiles();
		QString selected;
		if(!files.isEmpty())
			selected = files[0];
		ui.deployFileEdit->setText(QDir::current().relativeFilePath(selected));

		QFileInfo info(selected);
		temps.setLastDeployDir(info.dir().absolutePath());
	}
}
