# -*- 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 urllib.parse import urljoin

import requests

from qgis.PyQt import uic, QtWidgets
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QMessageBox, QCompleter

from .network_store_core import load_network_from_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_GET, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "network_store_dialog_get.ui")
)


class NetworkStorePluginDialogGet(QtWidgets.QDialog, FORM_CLASS_GET):
    def __init__(self, parent=None):
        """Constructor."""
        super(NetworkStorePluginDialogGet, 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.comboBox_networkID.setEditable(True)
        self.pushButton_refresh.clicked.connect(self.fetch_and_fill_network_ids)
        self.mLineEdit_baseURL.setValue("http://127.0.0.1:8888")
        self.comboConfig.currentIndexChanged.connect(self._apply_selected_config)
        self._reload_configs()
        self._reload_style_sets()

    def _normalized_base(self) -> str:
        base = (self.mLineEdit_baseURL.text() or "").strip()
        # accept with or without scheme
        if base and not base.startswith(("http://", "https://")):
            base = "http://" + base
        return base.rstrip("/")

    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)

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

    def fetch_and_fill_network_ids(self):
        base = self._normalized_base()
        if not base:
            QMessageBox.warning(
                self, "Missing Base URL", "Please enter the Base URL first."
            )
            return

        url = urljoin(base + "/", "network-store/networks")
        try:
            r = requests.get(url, timeout=10)
            r.raise_for_status()
            data = r.json()
        except Exception as e:
            QMessageBox.critical(
                self, "Fetch failed", f"Could not fetch networks from:\n{url}\n\n{e}"
            )
            return

        # normalize to a flat list of ids
        if isinstance(data, list):
            ids = [str(x) for x in data]
        elif isinstance(data, dict):
            for key in ("items", "networks", "data", "ids"):
                if isinstance(data.get(key), list):
                    ids = [str(x) for x in data[key]]
                    break
            else:
                ids = [str(k) for k in data.keys()]
        else:
            ids = []

        # fill combo + completer
        self.comboBox_networkID.blockSignals(True)
        self.comboBox_networkID.clear()
        self.comboBox_networkID.addItems(ids)
        self.comboBox_networkID.blockSignals(False)

        comp = QCompleter(ids, self)
        comp.setCaseSensitivity(Qt.CaseInsensitive)
        comp.setFilterMode(Qt.MatchContains)
        self.comboBox_networkID.setCompleter(comp)

    def get_network(self) -> tuple[list, list, list, list, bool]:
        #     # get ui member vars
        #     network_id = (self.comboBox_networkID.currentText() or "").strip()
        #     base_url   = self._normalized_base()# This is the network-store endpoint eg: localhost:8000/analytics/network-store

        #     if not network_id or not base_url:
        #         QMessageBox.warning(self, "Missing info", "Please set Base URL and Network ID.")
        #         return ([], [], [], [], False)
        """
        Thin wrapper around the shared backend.

        Called when the user clicks OK on the dialog.
        """

        network_id = (self.comboBox_networkID.currentText() or "").strip()
        base_url = self._normalized_base()

        if not network_id or not base_url:
            QMessageBox.warning(
                self, "Missing info", "Please set Base URL and Network ID."
            )
            return ([], [], [], [], False)

        nodes, links, polys, ctrls, ok = load_network_from_store(
            base_url,
            network_id,
            style_set=(self.comboStyleSet.currentText() or "").strip() or None,
            feedback=None,
        )

        if not ok:
            QMessageBox.information(
                self,
                "Network load",
                "No layers were loaded for this network. Check the log panel for details.",
            )

        return (nodes, links, polys, ctrls, ok)
