#include "database_window.h"
#include <QScrollBar>
#include <QFileDialog>
#include <QInputDialog>
#include <QImageReader>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QBuffer>


SHDesignerDatabase::SHDesignerDatabase(QWidget * parent): QMainWindow(parent), Ui::SHDesignerDatabase() {
	setupUi(this);
	connect(SHCORE, SIGNAL(databaseResaveRequest()), this, SLOT(resave()));
	auto * menu = new QMenu();
	menu->addActions({actionImportFile, actionImportServer});
	buttonImport->setMenu(menu);
	menu = new QMenu();
	menu->addActions({actionExportFile, actionExportServer});
	buttonExport->setMenu(menu);
	last_host = "shs.tools";
}


SHDesignerDatabase::~SHDesignerDatabase() {
}


void SHDesignerDatabase::closeEvent(QCloseEvent *) {
	SHCORE->reloadDB();
}


void SHDesignerDatabase::on_buttonRecreate_clicked() {
	QDialog dlg;
	QLayout * lay = new QBoxLayout(QBoxLayout::TopToBottom, &dlg);
	lay->addWidget(new QLabel("Select tables:"));
	QStringList tl = QSqlDatabase::database().tables();
	QList<QCheckBox*> tchecks;
	foreach (const QString & t, tl) {
		QCheckBox * cb = new QCheckBox(t);
		tchecks << cb;
		lay->addWidget(cb);
	}
	QDialogButtonBox * bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
	connect(bb, SIGNAL(accepted()), &dlg, SLOT(accept()));
	connect(bb, SIGNAL(rejected()), &dlg, SLOT(reject()));
	lay->addItem(new QSpacerItem(1, 1, QSizePolicy::Preferred, QSizePolicy::Expanding));
	lay->addWidget(bb);
	if (dlg.exec() == QDialog::Rejected) return;
	foreach (QCheckBox * c, tchecks) {
		if (c->isChecked()) {
			QSqlQuery q(QString("DROP TABLE %1").arg(c->text()));
		}
	}
	SHDatabaseStorage::initDatabase(SHCORE->database());
	reload();
}


void SHDesignerDatabase::on_actionImportFile_triggered() {
	if (path_imp.isEmpty()) path_imp = SHCORE->databasesDir().path();
	QString p = QFileDialog::getOpenFileName(this, "Select file to import", path_imp, "SHS database(*.shsdb)");
	if (p.isEmpty()) return;
	if (!p.endsWith(".shsdb")) p += ".shsdb";
	QFile file(p);
	if (!file.open(QIODevice::ReadOnly)) {
		QMessageBox::critical(this, "SH Designer", QString("Can`t open \"%1\"!").arg(p));
		return;
	}
	file.close();
	QSqlDatabase edb = QSqlDatabase::addDatabase("QSQLITE", "db_external");
	edb.setDatabaseName(p);
	if (!edb.open()) {
		QMessageBox::critical(this, "SH Designer", QString("Can`t open database \"%1\"!").arg(p));
		return;
	}
	if (ext_db.showImport(edb)) reload();
	edb.close();
	QSqlDatabase::removeDatabase("db_external");
	path_imp = p;
}


void SHDesignerDatabase::on_actionExportFile_triggered() {
	if (path_exp.isEmpty()) path_exp = SHCORE->databasesDir().path();
	QString p = QFileDialog::getSaveFileName(this, "Select file to export", path_exp, "SHS database(*.shsdb)");
	if (p.isEmpty()) return;
	if (!p.endsWith(".shsdb")) p += ".shsdb";
	QFile file(p);
	QSqlDatabase edb = QSqlDatabase::addDatabase("QSQLITE", "db_external");
	if (!file.open(QIODevice::ReadWrite)) {
		QMessageBox::critical(this, "SH Designer", QString("Can`t open \"%1\"!").arg(p));
		return;
	}
	file.close();
	edb.setDatabaseName(p);
	if (!edb.open()) {
		QMessageBox::critical(this, "SH Designer", QString("Can`t open database \"%1\"!").arg(p));
		return;
	}
	ext_db.showExport(edb);
	edb.close();
	QSqlDatabase::removeDatabase("db_external");
	path_exp = p;

}


void SHDesignerDatabase::on_actionImportServer_triggered() {
	QString host = QInputDialog::getText(this, tr("Import from server"), tr("Input server address:"), QLineEdit::Normal, last_host);
	if (last_host.isEmpty()) return;
	QApplication::setOverrideCursor(Qt::WaitCursor);
	QSqlDatabase edb = QSqlDatabase::addDatabase("QMYSQL", "db_external");
	edb.setHostName(last_host);
	edb.setUserName(mysql_user_read);
	edb.setDatabaseName(mysql_database);
	if (!edb.open()) {
		QApplication::restoreOverrideCursor();
		QMessageBox::critical(this, "SH Designer", QString("Can`t open database \"%1\"!").arg(last_host));
		return;
	}
	QApplication::restoreOverrideCursor();
	if (ext_db.showImport(edb)) reload();
	edb.close();
	QSqlDatabase::removeDatabase("db_external");
	last_host = host;
}


void SHDesignerDatabase::on_actionExportServer_triggered() {
	QString host = QInputDialog::getText(this, tr("Export to server"), tr("Input server address:"), QLineEdit::Normal, last_host);
	if (last_host.isEmpty()) return;
	QString pass = QInputDialog::getText(this, tr("Export to server"), tr("Input password:"), QLineEdit::Password);
	QApplication::setOverrideCursor(Qt::WaitCursor);
	QSqlDatabase edb = QSqlDatabase::addDatabase("QMYSQL", "db_external");
	edb.setHostName(last_host);
	edb.setUserName(mysql_user_write);
	edb.setPassword(pass);
	edb.setDatabaseName(mysql_database);
	if (!edb.open()) {
		QApplication::restoreOverrideCursor();
		QMessageBox::critical(this, "SH Designer", QString("Can`t open database \"%1\"!").arg(last_host));
		return;
	}
	QApplication::restoreOverrideCursor();
	ext_db.showExport(edb);
	edb.close();
	QSqlDatabase::removeDatabase("db_external");
	last_host = host;
}


void SHDesignerDatabase::reload(bool emit_changed) {
	iconPath->setToolTip(SHCORE->database().databaseName());
	tabBuses->reload();
	tabDevices->reload();
	tableVendors->updateTable(true);
	tableGroups->updateTable(true);
	if (emit_changed)
		QMetaObject::invokeMethod(SHCORE, "changed");
}


void SHDesignerDatabase::resave() {
	tabDevices->resaveAll();
}
