#include "networkcfgdialog.h"
#include "ui_networkcfgdialog.h"
#include "device/networkmanager.h"
#include "network/netcfgtablemodel.h"
#include "network/getipdialog.h"
#include "network/getroutedialog.h"

#include <QItemSelectionModel>
#include <QGraphicsDropShadowEffect>

#include "guimessagedialog.h"

#include <QThread>
networkCfgDialog::networkCfgDialog(QWidget* parent) :
	QDialog(parent),
	ui(new Ui::networkCfgDialog)
{
	ui->setupUi(this);
	this->setObjectName("formDialog");
	this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);

	msgDialog = new GUIMessageDialog(this);
	msgDialog->hide();

	ui->sw_dhcp->setChecked(true);
	//ui->sw_dhcp->setButtonStyle(ImageSwitch::ButtonStyle_1);


	model_addr = new NetCfgTableModel(this);
	model_route = new NetCfgTableModel(this);

	QStringList header_addr;
	header_addr << tr("IP Address") << tr("Netmask");
	model_addr->setHeader(header_addr);
	QStringList route_addr;
	route_addr << tr("Destination") << tr("Gateway") << tr("Netmask");
	model_route->setHeader(route_addr);

	ui->btn_group->button(QDialogButtonBox::Apply)->setText(tr("Apply"));
	ui->btn_group->button(QDialogButtonBox::Cancel)->setText(tr("Cancel"));

	loadData();

	ui->tbl_addr->setModel(model_addr);
	ui->tbl_route->setModel(model_route);

	//ui->tbl_addr->setAlternatingRowColors(true);
	ui->tbl_addr->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->tbl_addr->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tbl_addr->setEditTriggers(QAbstractItemView::NoEditTriggers);
	//ui->tbl_addr->verticalHeader()->setDefaultSectionSize(38);
	ui->tbl_addr->horizontalHeader()->setStretchLastSection(true);
	ui->tbl_addr->setColumnWidth(0, 345);
	ui->tbl_addr->setColumnWidth(1, 345);
	ui->tbl_addr->horizontalHeader()->setFixedHeight(38);

	//ui->tbl_route->setAlternatingRowColors(true);
	ui->tbl_route->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->tbl_route->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tbl_route->setEditTriggers(QAbstractItemView::NoEditTriggers);
	ui->tbl_route->verticalHeader()->setDefaultSectionSize(38);
	ui->tbl_route->horizontalHeader()->setStretchLastSection(true);
	ui->tbl_route->setColumnWidth(0, 230);
	ui->tbl_route->setColumnWidth(1, 230);
	ui->tbl_route->setColumnWidth(2, 230);
	ui->tbl_route->horizontalHeader()->setFixedHeight(38);


	connect(ui->btn_addr_add, &QPushButton::clicked, [=]()
		{
			//GetIPDialog* dialog = new GetIPDialog(this);
			GetIPDialog dialog(this);
			if (dialog.exec() == QDialog::Accepted)
			{
				model_addr->addRow(dialog.getList());
				//ui->tbl_addr->selectRow(0);
			}
		});
	connect(ui->btn_addr_edit, &QPushButton::clicked, [=]()
		{

			QItemSelectionModel* select = ui->tbl_addr->selectionModel();
			if (select->hasSelection())
			{
				QModelIndexList index = select->selectedRows();
				if (!index.empty()) {
					const QStringList ipdata = model_addr->rowData(index.at(0));

					//GetIPDialog* dialog = new GetIPDialog(this);
					GetIPDialog dialog(this);
					dialog.setList(ipdata);
					if (dialog.exec() == QDialog::Accepted)
					{
						model_addr->removeRow(index.at(0).row());
						model_addr->insertRow(index.at(0).row(), dialog.getList());

					}
				}
			}
		});

	connect(ui->btn_addr_del, &QPushButton::clicked, [=]()
		{
			QItemSelectionModel* select = ui->tbl_addr->selectionModel();
			if (select->hasSelection())
			{
				QModelIndexList index = select->selectedRows();
				if (!index.empty()) {
					model_addr->removeRow(index.at(0).row());

				}
			}
		});


	connect(ui->btn_route_add, &QPushButton::clicked, [=]()
		{
			//GetRouteDialog* dialog = new GetRouteDialog(this);
			GetRouteDialog dialog(this);
			if (dialog.exec() == QDialog::Accepted)
			{
				model_route->addRow(dialog.getList());
			}

		});
	connect(ui->btn_route_edit, &QPushButton::clicked, [=]()
		{

			QItemSelectionModel* select = ui->tbl_route->selectionModel();
			if (select->hasSelection())
			{
				QModelIndexList index = select->selectedRows();
				if (!index.empty()) {
					const QStringList ipdata = model_route->rowData(index.at(0));

					//GetRouteDialog* dialog = new GetRouteDialog(this);
					GetRouteDialog dialog(this);
					dialog.setList(ipdata);
					if (dialog.exec() == QDialog::Accepted)
					{
						model_route->removeRow(index.at(0).row());
						model_route->insertRow(index.at(0).row(), dialog.getList());

					}
				}
			}
		});

	connect(ui->btn_route_del, &QPushButton::clicked, [=]()
		{
			QItemSelectionModel* select = ui->tbl_route->selectionModel();
			if (select->hasSelection())
			{
				QModelIndexList index = select->selectedRows();
				if (!index.empty()) {
					model_route->removeRow(index.at(0).row());
				}
			}
		});
	connect(ui->btn_group->button(QDialogButtonBox::Apply), &QPushButton::clicked, [=]()
		{
			applyData();
		});
	connect(ui->btn_group->button(QDialogButtonBox::Cancel), &QPushButton::clicked, [=]()
		{
			reject();
		});
	ui->tabWidget->setCurrentIndex(0);
}




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



void networkCfgDialog::loadData()
{

	ui->led_inface->setText(NetworkManager::interfaceName());
	//ui->led_inface->setDisabled(true);
	ui->sw_dhcp->setChecked(NetworkManager::isDHCP());
	const IpAddr& default_addr = NetworkManager::getDefaultIpAddr();
	ui->addr_ip->setText(default_addr.ip);
	ui->addr_mask->setText(default_addr.mask);
	ui->led_gw->setText(NetworkManager::getDefaultGateway());
	model_addr->loadData(NetworkManager::getIpAddrList());
	model_route->loadData(NetworkManager::getIpRouteList());

	loadJsonData();
}

bool networkCfgDialog::isJsonModified()
{
	const host& h = NetworkManager::getLocalHost();
	if (ui->daq_AE->text() != h.ae) return true;
	if (ui->daq_Name->text() != h.name) return true;
	if (ui->daq_Port->text() != h.port)return true;
	return false;
}

void networkCfgDialog::loadJsonData()
{

	const host& h = NetworkManager::getLocalHost();
	ui->daq_AE->setText(h.ae);
	ui->daq_IP->setText(h.ip);
	ui->daq_Name->setText(h.name);
	ui->daq_Port->setText(h.port);
}

void networkCfgDialog::saveJsonData()
{
	host h;
	h.ip = ui->daq_IP->text();
	h.ae = ui->daq_AE->text();
	h.name = ui->daq_Name->text();
	h.port = ui->daq_Port->text();
	NetworkManager::setLocalHost(h);
}

bool networkCfgDialog::isNetModified()
{
	if (ui->sw_dhcp->getChecked() != NetworkManager::isDHCP()) return true;

	const IpAddr& default_addr = NetworkManager::getDefaultIpAddr();
	if (ui->addr_ip->text() != default_addr.ip) return true;
	if (ui->addr_mask->text() != default_addr.mask) return true;
	if (ui->led_gw->text() != NetworkManager::getDefaultGateway())return true;

	if (model_addr->getData() != NetworkManager::getIpAddrList())return true;
	if (model_route->getData() != NetworkManager::getIpRouteList()) return true;
	return false;
}



void networkCfgDialog::afterThreadStart()
{
	msgDialog->showMessage("Saving Network Configuration...");
	msgDialog->show();
}
void networkCfgDialog::beforeThreadExit()
{
	msgDialog->hide();
	ui->output->setPlainText(err);
	myThread->deleteLater();
}

void networkCfgDialog::applyData()
{
	if (isJsonModified())
	{
		saveJsonData();
	}
	//if it is the same as the old, just exit
	if (!isNetModified())
	{
		accept();
		return;
	}
	ui->tabWidget->setCurrentIndex(2);



	myThread = QThread::create([=]()
		{
			err.clear();
			err.append("restart\t\t");

			bool ret = NetworkManager::restart(err);
			//bool ret =true;
			//err.append(boolToStr(ret));

			err.append("\n");
			if (ui->sw_dhcp->getChecked())
			{
				NetworkManager::setJsonDHCP(true);
				err.append("network setting\t");
				err.append(boolToStr(ret));
			}
			else
			{
				NetworkManager::setJsonDHCP(false);

				IpAddr de_ipa;
				de_ipa.ip = ui->addr_ip->text();
				de_ipa.mask = ui->addr_mask->text();
				err.append("setDefaultIpAddr\t");
				bool ret1 = NetworkManager::setDefaultIpAddr(de_ipa, err);
				err.append("setDefaultGateway\t");
				bool ret2 = NetworkManager::setDefaultGateway(ui->led_gw->text(), err);
				err.append("setIpAddrList\t");
				bool ret3 = NetworkManager::setIpAddrList(model_addr->getData(), err);
				err.append("setIpRouteList\t");
				bool ret4 = NetworkManager::setIpRouteList(model_route->getData(), err);
				err.append("\n").append("network settings\t");

				bool retAll = ret & ret1 & ret2 & ret3 & ret4;
				err.append(boolToStr(retAll));
			}



		});

	connect(myThread, SIGNAL(started()), this, SLOT(afterThreadStart()));
	connect(myThread, SIGNAL(finished()), this, SLOT(beforeThreadExit()));

	myThread->start();


}



