# -*- coding: utf-8 -*-
"""
/***************************************************************************
 NetworkStorePluginDialog
                                 A QGIS plugin
 export layers to kisters network store
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2022-01-18
        git sha              : $Format:%H$
        copyright            : (C) 2022 by Attila Bibok
        email                : Attila.bibok@kisters.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 import QtWidgets

from .network_store_core import create_network_in_store, list_style_sets
from .network_store_settings import NetworkStoreSettingsStore

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS_POST, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "network_store_dialog_post.ui")
)


class NetworkStorePluginDialogPost(QtWidgets.QDialog, FORM_CLASS_POST):
    def __init__(self, parent=None):
        """Constructor."""
        super(NetworkStorePluginDialogPost, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.comboConfig.currentIndexChanged.connect(self._apply_selected_config)
        if hasattr(self, "checkBoxLoadNetwork"):
            self.checkBoxLoadNetwork.toggled.connect(self._toggle_style_set)
        self._reload_configs()
        self._reload_style_sets()

    def _normalized_base(self) -> str:
        """
        Return the base URL stripped and without trailing slashes.
        """
        return (self.mLineEdit_baseURL.text() or "").strip().rstrip("/")

    def _network_id(self) -> str:
        return (self.mLineEdit_networkID.text() or "").strip()

    def _reload_configs(self) -> None:
        store = NetworkStoreSettingsStore()
        configs = store.list()
        self.comboConfig.blockSignals(True)
        self.comboConfig.clear()
        for cfg in configs:
            label = f"{cfg.name} ({cfg.base_url})"
            self.comboConfig.addItem(label, cfg)
        self.comboConfig.blockSignals(False)
        if self.comboConfig.count() > 0:
            self.comboConfig.setCurrentIndex(0)
            self._apply_selected_config()

    def _reload_style_sets(self) -> None:
        self.comboStyleSet.blockSignals(True)
        self.comboStyleSet.clear()
        for name in list_style_sets():
            self.comboStyleSet.addItem(name)
        self.comboStyleSet.blockSignals(False)
        default_idx = self.comboStyleSet.findText("default")
        if default_idx >= 0:
            self.comboStyleSet.setCurrentIndex(default_idx)
        self._toggle_style_set()

    def _toggle_style_set(self) -> None:
        if hasattr(self, "checkBoxLoadNetwork"):
            enabled = bool(self.checkBoxLoadNetwork.isChecked())
            self.comboStyleSet.setEnabled(enabled)
            if hasattr(self, "label_styleSet"):
                self.label_styleSet.setEnabled(enabled)

    def _apply_selected_config(self) -> None:
        idx = self.comboConfig.currentIndex()
        cfg = self.comboConfig.itemData(idx)
        if cfg is None:
            return
        self.mLineEdit_baseURL.setText(str(cfg.base_url or "").strip())

    def create_network(self) -> bool:
        """
        Create a new network in the store (and optionally load it).

        Returns True on success, False otherwise.
        """
        base_url = self._normalized_base()
        network_id = self._network_id()
        load_network = getattr(self, "checkBoxLoadNetwork", None)
        load_network = (
            bool(load_network.isChecked()) if load_network is not None else True
        )

        if not base_url or not network_id:
            QtWidgets.QMessageBox.warning(
                self,
                self.tr("Missing information"),
                self.tr("Please provide both Base URL and Network ID."),
            )
            return False

        ok = create_network_in_store(
            base_url,
            network_id,
            load_network=load_network,
            style_set=(self.comboStyleSet.currentText() or "").strip() or None,
            feedback=None,
        )

        if not ok:
            QtWidgets.QMessageBox.critical(
                self,
                self.tr("Create network failed"),
                self.tr(
                    "Creating the network in the store failed.\n"
                    "Check the NetworkStore log panel for details."
                ),
            )
            return False

        if load_network:
            msg = self.tr(
                "Network '{0}' was created in the store and loaded into the project."
            ).format(network_id)
        else:
            msg = self.tr("Network '{0}' was created in the store.".format(network_id))

        QtWidgets.QMessageBox.information(self, self.tr("Network created"), msg)
        return True
