/* $Header: $ */

/* Patrick J. Thomas, California Institute of Technology, LIGO Hanford */


// For testing: gst-launch-1.0 videotestsrc ! video/x-raw,format=GRAY8 ! videoconvert ! x264enc pass=qual quantizer=20 tune=zerolatency ! rtph264pay ! udpsink host=224.1.1.1 port=5000

// It seems that g_signal_connect needs to be called before QObject::connect.

#include <QApplication>

#include <QCommandLineParser>

#include <iostream>

#include "mainwindow.h"
#include "acquisitiontype.h"

int main(int argc, char *argv[]) {
	QApplication app(argc, argv);

	app.setApplicationVersion("2.3");

	QCommandLineParser parser;

	guint64 udp_timeout;
	const QString default_udp_timeout = "1";

	QString label_font;
	const QString default_label_font = "Courier";

	qreal label_point_size;
	const QString default_label_point_size = "14";
	const qreal min_label_point_size = 6;
	const qreal max_label_point_size = 72;

	QStringList args;

	const unsigned short expected_args_count = 3;

	QString address;
	QString port;
	QString label_text;


	parser.addVersionOption();
	parser.addHelpOption();


	QCommandLineOption udp_timeoutOption("t", "UDP timeout (sec)", "timeout", default_udp_timeout);
	parser.addOption(udp_timeoutOption);

	QCommandLineOption label_fontOption("f", "Label font", "font", default_label_font);
	parser.addOption(label_fontOption);

	QCommandLineOption label_point_sizeOption("s", "Label point size", "size", default_label_point_size);
	parser.addOption(label_point_sizeOption);

	parser.addPositionalArgument("address", "Address");
	parser.addPositionalArgument("port", "Port");
	parser.addPositionalArgument("label", "Label text");

	parser.process(app);

	udp_timeout = parser.value(udp_timeoutOption).toUInt();
	udp_timeout *= 1E9;

	label_font = parser.value(label_fontOption);

	label_point_size = parser.value(label_point_sizeOption).toDouble();
	label_point_size = label_point_size > min_label_point_size ? label_point_size : min_label_point_size;
	label_point_size = label_point_size < max_label_point_size ? label_point_size : max_label_point_size;

	args = parser.positionalArguments();

	if (args.count() < expected_args_count) {
		std::cout << parser.helpText().toLatin1().data() << std::endl;
		std::cout << "error: too few arguments" << std::endl;
		return -1;
	}
	else if (args.count() > expected_args_count) {
		std::cout << parser.helpText().toLatin1().data() << std::endl;
		std::cout << "error: unrecognized arguments: " << QStringList(args.mid(expected_args_count, -1)).join(" ").toLatin1().data() << std::endl;
		return -1;
	}

	address = args.at(0);
	port = args.at(1);
	label_text = args.at(2);


	AcquisitionType acquisition(address.toLatin1(), port.toInt(), udp_timeout);

	MainWindow window(label_text, label_font, label_point_size);

	QObject::connect(&acquisition, SIGNAL(setData(const QPixmap&)), &window, SLOT(setData(const QPixmap&)));

	window.show();

	return app.exec();
}

