#include "tycho.h"

Menu::Menu(QWidget *parent) :
	QMainWindow(parent)
{
	setupUi(this);

	setWindowIcon(::getIcon("pfhor-hand"));

	actionAbout->setShortcut(QKeySequence(QKeySequence::HelpContents));
	actionClose->setShortcut(QKeySequence(QKeySequence::Close));
	actionMapProps->setShortcut(QKeySequence(tr("Ctrl+P")));
	actionNew->setShortcut(QKeySequence(QKeySequence::New));
	actionOpen->setShortcut(QKeySequence(QKeySequence::Open));
	actionQuit->setShortcut(QKeySequence(QKeySequence::Quit));

	dbgPrintFunc();
}

Menu::~Menu()
{
	dbgPrintFunc();
}

void Menu::mapNew()
{
	QScopedPointer proj{new Project(Project::Map)};

	addProject(proj.take());
}

void Menu::mapOpen()
{
	auto fname =
		QFileDialog::getOpenFileName(
			this,
			tr("Open Map File"),
			QString(),
			tr("Marathon Map files (*.scen *.sceA Map);;"
			   "Marathon Physics files (*.phys *.phyA Physics);;"
			   "Aleph One Image files (*.imgA);;"
			   "All files (*)"));

	if(!fname.isEmpty()) {
		QScopedPointer proj{new Project(Project::Map)};

		if(proj->model()->open(fname)) {
			addProject(proj.take());
		}
	}
}

void Menu::openAbout()
{
	QDialog   dlg{this};
	Ui::About ui{};

	ui.setupUi(&dlg);

	auto text = ui.labelText->text();

	text.replace("AUTHORS",
	             tr(::tychoAuthors()).replace(':', ", ").toHtmlEscaped());
	text.replace("HOMEPAGE", tr(::tychoHomepage()));
	text.replace("REPOSITORY", tr(::tychoRepository()));
	text.replace("VERSION", tr(::tychoVersion()));

	ui.labelText->setText(text);

	connect(ui.btnLicense, &QPushButton::clicked, this, [&](){
		openLicense(&dlg);
	});

	dlg.exec();
}

void Menu::openAboutQt()
{
	QMessageBox::aboutQt(this);
}

void Menu::openLicense(QWidget *parent)
{
	QDialog     dlg{parent};
	Ui::License ui{};

	ui.setupUi(&dlg);

	ui.text->setPlainText(tychoLicenseText());

	connect(ui.btnCopy, &QPushButton::clicked, this, [&]() {
		ui.text->selectAll();
		ui.text->copy();
	});

	dlg.exec();
}

void Menu::openMapProperties()
{
	auto proj = activeProject();

	if(proj && proj->type() == Project::Map) {
		MapProps props{proj};
		props.exec();
	}
}

void Menu::updateActions()
{
	std::optional<Project::Type> active;

	if(auto proj = activeProject()) {
		active = proj->type();
	}

	actionClose->setEnabled(!!active);
	actionMapProps->setEnabled(active == Project::Map);
}

void Menu::closeEvent(QCloseEvent *event)
{
	for(auto *win : mdiArea->subWindowList()) {
		if(!win->close()) {
			event->ignore();
			return;
		}
	}

	event->accept();
}

Project *Menu::activeProject() const
{
	return qobject_cast<Project *>(activeSubWindow());
}

QMdiSubWindow *Menu::activeSubWindow() const
{
	return mdiArea->activeSubWindow();
}

void Menu::addProject(Project *proj)
{
	auto win = mdiArea->addSubWindow(proj);

	win->showMaximized();
}

// EOF
