#include "mainwindow.h"

#include <QMessageBox>
#include <QInputDialog>

#include "ui_mainwindow.h"
#include "itemscrollbox.h"
#include "itemsettingsdialog.h"
#include "itemcreationdialog.h"
#include "mainobject.h"
#include "programmode.h"
#include "items/poweritem.h"
#include "sensors/mqttsensorsource.h"

MainWindow::MainWindow(MainObject * const mainObject, QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow),
	mainObject(mainObject),
	colorChooser(this)
{
	ui->setupUi(this);
	connect(ui->pushButton_broadcast, &QPushButton::clicked, this, &MainWindow::sigSave);
	connect(ui->pushButton_broadcast, &QPushButton::clicked, this, [this](){QMessageBox::information(this, "Saved", "Settings where saved");});

	connect(ui->pushButton_power, SIGNAL(clicked()), this, SLOT(showPowerItemDialog()));

	connect(ui->pushButton_refesh, &QPushButton::clicked, mainObject, &MainObject::refresh);
	connect(&globalItems, &ItemStore::itemAdded, ui->relayList, &ItemScrollBox::addItem);
	connect(&globalItems, &ItemStore::itemDeleted, ui->relayList, &ItemScrollBox::removeItem);
	connect(&globalItems, &ItemStore::itemUpdated, ui->relayList, &ItemScrollBox::onItemUpdate);

	for(size_t i = 0; i < globalItems.getItems()->size(); ++i)
		ui->relayList->addItem(globalItems.getItems()->at(i));

	if(programMode != PROGRAM_MODE_PRIMARY)
		ui->label_serialRecive->setHidden(true);

	//Sensors
	ui->sensorListView->setShowHidden(false);
	ui->sensorListView->sensorsChanged(*globalSensors.getSensors());
	connect(&globalSensors, &SensorStore::stateChenged, ui->sensorListView, &SensorListWidget::sensorsChanged);

	//RGB Leds
	connect(&colorChooser, &QColorDialog::colorSelected, this, &MainWindow::sigSetRgb);
	connect(ui->button_quit, SIGNAL(clicked()), this, SLOT(close()));
	connect(ui->button_color, SIGNAL(clicked()), &colorChooser, SLOT(show()));
	if(programMode != PROGRAM_MODE_PRIMARY)
		ui->button_color->hide();

	connect(ui->pushButton_addItem, &QPushButton::clicked, this, &MainWindow::showItemCreationDialog);
	connect(ui->pushButton_addSensor, &QPushButton::clicked, this, &MainWindow::showSensorCreationDialog);
	connect(ui->relayList, &ItemScrollBox::deleteRequest, &globalItems, &ItemStore::removeItem);
	connect(ui->checkBox_sensorsShowHidden, &QCheckBox::clicked, ui->sensorListView, &SensorListWidget::setShowHidden);

	ui->splitter->setStretchFactor(1, 1);
}

MainWindow::~MainWindow()
{
	delete ui;
}

void MainWindow::showPowerItemDialog()
{
	std::shared_ptr<PowerItem> powerItem;
	for(std::shared_ptr<Item> item : *globalItems.getItems())
	{
		powerItem = std::dynamic_pointer_cast<PowerItem>(item);
		if(powerItem)
			break;
	}
	if(powerItem)
	{
		ItemSettingsDialog diag(std::shared_ptr<Item>(powerItem), false, this);
		diag.show();
		diag.exec();
	}
	else
	{
		QMessageBox::warning(this, "Error", "No power item found, refresh first");
	}
}
void MainWindow::showItemCreationDialog()
{
	ItemCreationDialog diag(this);
	diag.show();
	if(diag.exec())
	{
		ItemAddRequest request;
		request.type = ITEM_UPDATE_USER;
		request.changes = ItemFieldChanges(true);
		request.payload = diag.item;
		createdItem(request);
	}
}

void MainWindow::showSensorCreationDialog()
{
	bool ok;
	QString topic = QInputDialog::getText(this, "Add MQTT Sensor", "Topic:", QLineEdit::Normal, "", &ok);
	if(!ok || topic.isEmpty())
		return;

	QString name = QInputDialog::getText(this, "Add MQTT Sensor", "Name:", QLineEdit::Normal, topic, &ok);
	if(!ok)
		return;

	Sensor sensor(Sensor::TYPE_DUMMY, 0, 0, name);
	QJsonObject payload;
	payload["Topic"] = topic;
	payload["Name"] = name;

	PrimaryMainObject* primaryMain = dynamic_cast<PrimaryMainObject*>(mainObject);
	if(primaryMain)
	{
		// Primary mode: add directly to mqttSensorSource
		primaryMain->mqttSensorSource.addSensor(topic, name);
	}
	else
	{
		// Secondary mode: send via TCP to primary
		mainObject->addSensor(sensor, Sensor::BACKEND_MQTT, payload);
	}
}

void MainWindow::changeHeaderLableText(QString string)
{
	if(string.size() > 28)
	{
		string.remove(28, string.size()-(28));
		string.append("...");
	}
	ui->label_serialRecive->setText(string);
}

void MainWindow::store(QJsonObject& json) const
{
	QJsonObject mainWindowJson;

	QList<int> splitterSizes = ui->splitter->sizes();
	QJsonArray splitterSizeArray;
	for(int size : splitterSizes)
		splitterSizeArray.append(size);
	mainWindowJson["SplitterSizes"] = splitterSizeArray;

	ui->relayList->store(mainWindowJson);
	ui->sensorListView->store(mainWindowJson);

	json["MainWindow"] = mainWindowJson;
}

void MainWindow::load(const QJsonObject& json)
{
	QJsonObject mainWindowJson = json["MainWindow"].toObject();

	QJsonArray splitterSizes = mainWindowJson["SplitterSizes"].toArray();
	if(!splitterSizes.isEmpty())
	{
		QList<int> sizes;
		for(const QJsonValue& size : splitterSizes)
			sizes.append(size.toInt());
		ui->splitter->setSizes(sizes);
	}

	ui->relayList->load(mainWindowJson);
	ui->sensorListView->load(mainWindowJson);
}
