#include "mainwindow.h"
#include "canvasview.h"
#include "contrastdialog.h"
#include "valuedialog.h"

#include <qfiledialog.h>
#include <qapplication.h>
#include <qaction.h>
#include <qfileinfo.h>

MainWindow::MainWindow() : m_contrastDialog(0), m_valueDialog(0) {
	connect(helpAboutQtAction, SIGNAL(activated()), qApp, SLOT(aboutQt()));
}

void MainWindow::openFile() {
	QString filename = QFileDialog::getOpenFileName();
	if (!filename.isNull()) {
		QFileInfo fi(filename);

		canvas->loadImage(filename);
		imageContrastAction->setEnabled(true);
		imageValuesAction->setEnabled(true);
		fileSaveAction->setEnabled(true);
		fileSaveAsAction->setEnabled(true);
		fileCloseAction->setEnabled(true);
		setCaption(QString("Bildbearbeitung - %1").arg(fi.fileName()));
	}
}

void MainWindow::contrastBrightness() {
	if (! m_contrastDialog) { // Dialog erst erstellen, wenn er benötigt wird.
		m_contrastDialog = new ContrastDialog(this);
		connect(m_contrastDialog, SIGNAL(curveChanged(std::valarray<int>)), canvas,
			SLOT(applyCurve(std::valarray<int>)));
	}
	switch(m_contrastDialog->exec()) {
		case QDialog::Accepted:
			canvas->commit();
			break;
		case QDialog::Rejected:
			canvas->rollback();
			break;
	}
}

void MainWindow::values() {
	if (! m_valueDialog) { // Dialog erst erstellen, wenn er benötigt wird.
		m_valueDialog = new ValueDialog(this);
		connect(m_valueDialog, SIGNAL(curveChanged(std::valarray<int>)), canvas,
				  SLOT(applyCurve(std::valarray<int>)));
	}
	switch(m_valueDialog->exec()) {
		case QDialog::Accepted:
			canvas->commit();
			break;
		case QDialog::Rejected:
			canvas->rollback();
			break;
	}
}

void MainWindow::closeFile() {
	canvas->closeImage();
	imageContrastAction->setEnabled(false);
	imageValuesAction->setEnabled(false);
	fileSaveAction->setEnabled(false);
	fileSaveAsAction->setEnabled(false);
	fileCloseAction->setEnabled(false);
	setCaption(QString("Bildbearbeitung - Keine Datei"));
}

void MainWindow::saveFile() {
	canvas->saveImage();
}

void MainWindow::saveFileAs() {
	QString filename = QFileDialog::getSaveFileName();
	if (!filename.isNull()) {
		canvas->setFileName(filename);
		canvas->saveImage();
		QFileInfo fi(filename);
		setCaption(QString("Bildbearbeitung - %1").arg(fi.fileName()));
	}
}

int main(int argc, char** argv) {
	QApplication app(argc, argv);
	MainWindow cv;
	app.setMainWidget(&cv);
	cv.show();
	return app.exec();
}
