#include "main_window.h"
#include "mesh_processor.h"
#include <iostream>
#include <QSurfaceFormat>
#include <QApplication>


static MeshProcessor *create_mesh_processor(const QString &path,
											MainWindow &main_window) {
	MeshViewer &mesh_viewer = main_window.mesh_viewer;
	MeshProcessor *mesh_processor = new MeshProcessor(path, mesh_viewer);
	QObject::connect(&main_window, &MainWindow::fillHolesDumbClicked,
					 mesh_processor, &MeshProcessor::fillHolesDumb);
	QObject::connect(&main_window, &MainWindow::fillHolesImplicitClicked,
					 mesh_processor, &MeshProcessor::fillHolesImplicit);
	QObject::connect(&main_window, &MainWindow::smoothClicked,
					 mesh_processor, &MeshProcessor::smooth);
	QObject::connect(&main_window, &MainWindow::patchViewToggled,
					 mesh_processor, &MeshProcessor::setPatchView);
	return mesh_processor;
}


int main(int argc, char *argv[]) {
	using namespace std;
	QSurfaceFormat format;
	format.setRenderableType(QSurfaceFormat::OpenGL);
#ifdef QT_DEBUG
	qDebug("Debug build");
	format.setOption(QSurfaceFormat::DebugContext);
#endif
	QSurfaceFormat::setDefaultFormat(format);
	QApplication app(argc, argv);
	MeshProcessor *mesh_processor = nullptr;
	MainWindow main_window;
	if (argc > 2) {
		qWarning("Utilisation : %s [MAILLAGE]", argv[0]);
		return 1;
	} else if (argc == 2) {
		mesh_processor = create_mesh_processor(argv[1], main_window);
	}
	QObject::connect(&main_window, &MainWindow::open,
					 [&](const QString &path) {
						 if (mesh_processor) delete mesh_processor;
						 mesh_processor = create_mesh_processor
							 (path, main_window);
					 });
	main_window.show();
	return app.exec();
}
