# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Infra3DSettings
                                 A QGIS plugin
 This plugin is an integration of the Infra3D application with QGIS
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-09-28
        git sha              : $Format:%H$
        copyright            : (C) 2022 by Sourcepole AG
        email                : hka@sourcepole.ch
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import os

from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QMainWindow, QDialog, QDialogButtonBox, QMessageBox
from qgis.PyQt.QtCore import QSettings


FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'ui/settings.ui'))


DEFAULT_SERVER_PORT = 5000
DEFAULT_PG_SERVER_PORT = 5432


class Infra3DSettings(QDialog, FORM_CLASS):

    def __init__(self, parent: QMainWindow):
        super(Infra3DSettings, self).__init__(parent)
        self.setupUi(self)
        self.settings = QSettings()
        self.buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.save_settings)
        self.buttonBox.button(QDialogButtonBox.Cancel).clicked.connect(self.prefill_from_settings)

        # Get values from settings and prefill dialog
        self.prefill_from_settings()

    def prefill_from_settings(self):
        """Fill lineedits in the settings dialog with values from QSettings or
        just use default values
        """
        # Infra3D credentials
        self.infra3d_username_lineEdit.setText(self.settings.value("/infra3d_viewer/infra3d_username"))
        self.infra3d_password_lineEdit.setText(self.settings.value("/infra3d_viewer/infra3d_password"))
        # SocketIO server
        self.server_port_spinBox.setValue(int(self.settings.value("/infra3d_viewer/server_port", DEFAULT_SERVER_PORT)))
        # Postgres server
        self.infra3d_groupBox.setChecked(bool(self.settings.value('/infra3d_viewer/load_pg_layer', False)))
        self.pg_host_lineEdit.setText(self.settings.value('/infra3d_viewer/database/host'))
        self.pg_port_spinBox.setValue(int(self.settings.value('/infra3d_viewer/database/port', DEFAULT_PG_SERVER_PORT)))
        self.pg_username_lineEdit.setText(self.settings.value('/infra3d_viewer/database/username'))
        self.pg_password_lineEdit.setText(self.settings.value('/infra3d_viewer/database/password'))
        self.pg_database_lineEdit.setText(self.settings.value('/infra3d_viewer/database/database'))
        self.pg_table_lineEdit.setText(self.settings.value('/infra3d_viewer/database/tablename'))
        self.pg_schema_lineEdit.setText(self.settings.value('/infra3d_viewer/database/schema'))
        self.pg_geom_lineEdit.setText(self.settings.value('/infra3d_viewer/database/geometry_column'))

    def save_settings(self):
        if self.server_port_spinBox.value() != int(self.settings.value("/infra3d_viewer/server_port", DEFAULT_SERVER_PORT)):
            QMessageBox.warning(
                None,  # type: ignore
                self.tr("Infra3D: Server port changed"),
                self.tr("Restart QGIS for the port change to take effect!")
            )

        # Infra3D credentials
        self.settings.setValue("/infra3d_viewer/infra3d_username", self.infra3d_username_lineEdit.text())
        self.settings.setValue("/infra3d_viewer/infra3d_password", self.infra3d_password_lineEdit.text())
        # SocketIO server
        self.settings.setValue("/infra3d_viewer/server_port", self.server_port_spinBox.value())
        # Postgres server
        self.settings.setValue('/infra3d_viewer/load_pg_layer', self.infra3d_groupBox.isChecked())
        self.settings.setValue('/infra3d_viewer/database/host', self.pg_host_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/port', self.pg_port_spinBox.value())
        self.settings.setValue('/infra3d_viewer/database/username', self.pg_username_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/password', self.pg_password_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/database', self.pg_database_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/tablename', self.pg_table_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/schema', self.pg_schema_lineEdit.text())
        self.settings.setValue('/infra3d_viewer/database/geometry_column', self.pg_geom_lineEdit.text())
