#include "designer_mainwindow.h"
#include "device_widget.h"
#include "SH_base.h"
#include <aboutwindow.h>
#include <picrypt.h>
#include <QApplication>
#include <QMessageBox>
#include <QTimer>


DesignerMainWindow::DesignerMainWindow(QString name, QWidget * parent): EMainWindow(parent), qsa(name) {
	initAbout();
	setObjectName(name);
	if (!qsa.isFirst()) {
		QByteArray msg; QDataStream s(&msg, QIODevice::ReadWrite);
		s << qApp->arguments();
		qsa.sendMessage(msg);
		return;
	}
	QObject::connect(&qsa, SIGNAL(messageReceived(QByteArray)), this, SLOT(anotherAppMessage(QByteArray)));
	session.setFile("session_" + name.toLower().replace(' ', '_') + ".conf");
	session.addEntry(this);
}


DesignerMainWindow::~DesignerMainWindow() {
	session.clear();
}


void DesignerMainWindow::initAbout() {
	Q_INIT_RESOURCE(shared);
	ADD_ABOUT_VERSION(SHS);
	AboutWindow::addVersion("Ui sync", QString::number(SHS_UISYNC_VERSION));
	ADD_ABOUT_VERSION(QAD);
	AboutWindow::addVersion("Qt", qVersion());
	ADD_ABOUT_VERSION(PIP);
	AboutWindow::addVersion("sodium", PI2QString(PICrypt::version()));
	ADD_ABOUT_BUILD_INFO(SHS);
}


bool DesignerMainWindow::procArgs(const QStringList & args, bool check) {
	if (args.size() <= 1) return false;
	QString dev;
	int addr = -1;
	bool was_load = false;
	for (int i = 1; i < args.size(); ++i) {
		if (args[i] == "-d") {
			++i;
			if (i < args.size()) {
				dev = args[i];
				if (!dev.isEmpty() && !check)
					setDevice(dev);
			}
			continue;
		}
		if (args[i] == "-a") {
			++i;
			if (i < args.size()) {
				addr = args[i].toInt();
				if (addr >= 0 && !check)
					setAddress(addr);
			}
			continue;
		}
		if (!check) {
			if (was_load) continue;
			was_load = true;
			loadFile(args[i]);
			continue;
		}
		return true;
	}
	return false;
}


void DesignerMainWindow::unchange() {
	setChanged(false);
}


void DesignerMainWindow::showAbout() {
	AboutWindow::show();
}


void DesignerMainWindow::loadFile(const QString & fp) {
	load(fp);
}


void DesignerMainWindow::showMain() {
	show();
	procArguments(qApp->arguments());
	procArgs(qApp->arguments());
	QTimer::singleShot(0, this, SLOT(unchange()));
}


bool DesignerMainWindow::isFirst() const {
	return qsa.isFirst();
}


void DesignerMainWindow::anotherAppMessage(QByteArray data) {
	QDataStream s(data);
	QStringList args; s >> args;
	if (args.isEmpty()) return;
	setFocus();
	activateWindow();
	raise();
	if (procArgs(args, true)) {
		if (QMessageBox::question(this, windowTitle(), "Open new file?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) != QMessageBox::Yes)
			return;
	}
	procArguments(args);
	procArgs(args);
}
