#include "profiledialog.h"
#include "ui_profiledialog.h"
#include "editprofiledialog.h"

#include <QMessageBox>

ProfileDialog::ProfileDialog(Cameras* cameras, QWidget *parent) :
	QDialog(parent),
	cameras_(cameras),
	ui(new Ui::ProfileDialog)
{
	ui->setupUi(this);
	ui->listWidget->addItems(Profile::avaiableProfiles());
	connect(ui->pushButtonAdd, &QPushButton::clicked, this, &ProfileDialog::addProfile);
	connect(ui->pushButtonEdit, &QPushButton::clicked, this, &ProfileDialog::editProfile);
	connect(ui->pushButtonDelete, &QPushButton::clicked, this, &ProfileDialog::deleteProfile);
}


ProfileDialog::~ProfileDialog()
{
	delete ui;
}

void ProfileDialog::editProfile()
{
	QList<QListWidgetItem *> items = ui->listWidget->selectedItems();
	if(items.size() > 0)
	{
		Profile profile;
		profile.load(items[0]->text());
		if(!profile.camerasSufficant(cameras_->getCameras()))
		{
			QMessageBox::critical(this, "Profile Incompatible", "Not all cameras need for this profile are available");
			return;
		}
		EditProfileDialog dialog(cameras_, profile, this);
		dialog.show();
		int ret = dialog.exec();
		if(ret == QDialog::Accepted)
		{
			dialog.getProfile().store();
			ui->listWidget->clear();
			ui->listWidget->addItems(Profile::avaiableProfiles());
		}
	}
}

void ProfileDialog::deleteProfile()
{
	QList<QListWidgetItem *> items = ui->listWidget->selectedItems();
	if(items.size() > 0)
	{
		Profile profile(items[0]->text());
		profile.deleteProfile();
		ui->listWidget->clear();
		ui->listWidget->addItems(Profile::avaiableProfiles());
	}
}

void ProfileDialog::addProfile()
{
	if(cameras_->getCameras().size() == 0)
	{
		QMessageBox::critical(this, "No Cameras", "At least one camera is needed to create a profile");
		return;
	}

	EditProfileDialog dialog(cameras_);
	dialog.show();
	int ret = dialog.exec();
	if(ret == QDialog::Accepted)
	{
		dialog.getProfile().store();
		ui->listWidget->clear();
		ui->listWidget->addItems(Profile::avaiableProfiles());
	}
}

