# -*- coding: utf-8 -*-
# Copyright (C) 2026 Mykhailo Krechkivskyi

#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
/***************************************************************************
 GeoJsonUaDockWidget
                                 A QGIS plugin
 Process Ukrainian GeoJSON files
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2026-02-28
        git sha              : $Format:%H$
        copyright            : (C) 2026 by Michael Krechkivsky
        email                : krechkivsky.dev@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 configparser
import os
from functools import partial

from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtCore import pyqtSignal, Qt

from . import common

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


class GeoJsonUaDockWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()
    request_geojson = pyqtSignal(str)

    def __init__(self, parent=None):
        """Constructor."""
        if common.LOG:
            common.log_calls(common.logFile, f"GeoJsonUaDockWidget.__init__(parent={type(parent).__name__ if parent else None})")
        super(GeoJsonUaDockWidget, self).__init__(parent)
        try:
            self.setMaximumWidth(300)
        except Exception:
            pass
        try:
            self.setObjectName("json_ua")
        except Exception:
            pass
        self._panel_name = "json_ua"
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://doc.qt.io/qt-5/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        try:
            self.dockWidgetContents.setMaximumWidth(300)
        except Exception:
            pass
        try:
            self.layerGroupsTabs.setMaximumWidth(300)
        except Exception:
            pass
        try:
            self.layerGroupsTabs.setUsesScrollButtons(True)
            self.layerGroupsTabs.setElideMode(Qt.ElideNone)
            self.layerGroupsTabs.tabBar().setExpanding(False)
        except Exception:
            pass
        try:
            self.toggleViewAction().setText(self._panel_name)
        except Exception:
            pass
        try:
            self.windowTitleChanged.connect(self._sync_panel_title)
        except Exception:
            pass
        self._populate_layer_tabs()

    def sizeHint(self):
        base = super(GeoJsonUaDockWidget, self).sizeHint()
        try:
            parent = self.parent()
            parent_width = parent.width() if parent is not None else 0
            if parent_width:
                max_width = int(parent_width * 0.35)
                if max_width < 280:
                    max_width = 280
                if max_width > 520:
                    max_width = 520
                if base.width() > max_width:
                    base.setWidth(max_width)
        except Exception:
            pass
        return base

    def _sync_panel_title(self, _title: str) -> None:
        try:
            self.toggleViewAction().setText(self._panel_name)
        except Exception:
            pass

    def _read_layer_names_ini(self):
        if common.LOG:
            common.log_calls(common.logFile, "GeoJsonUaDockWidget._read_layer_names_ini()")
        ini_path = os.path.join(os.path.dirname(__file__), "ini", "layer_names.ini")
        parser = configparser.ConfigParser(interpolation=None)
        parser.optionxform = str
        try:
            with open(ini_path, "r", encoding="utf-8") as handle:
                parser.read_file(handle)
        except UnicodeDecodeError:
            try:
                with open(ini_path, "r", encoding="cp1251") as handle:
                    parser.read_file(handle)
            except Exception:
                return None
        except Exception:
            return None
        return parser

    def _populate_layer_tabs(self) -> None:
        if common.LOG:
            common.log_calls(common.logFile, "GeoJsonUaDockWidget._populate_layer_tabs()")
        if not hasattr(self, "layerGroupsTabs"):
            return
        self.layerGroupsTabs.clear()
        parser = self._read_layer_names_ini()
        if parser is None or not parser.has_section("LayerGroups"):
            return
        groups = list(parser.items("LayerGroups"))
        for group_key, group_title in groups:
            rows = []
            if parser.has_section(group_key):
                rows = list(parser.items(group_key))
            table = QtWidgets.QTableWidget()
            table.setColumnCount(1)
            table.setRowCount(len(rows))
            table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
            table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
            table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
            table.setShowGrid(False)
            table.horizontalHeader().setStretchLastSection(True)
            table.horizontalHeader().setVisible(False)
            table.verticalHeader().setVisible(False)
            table.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            for row_index, (item_key, item_title) in enumerate(rows):
                item = QtWidgets.QTableWidgetItem(item_title)
                item.setData(Qt.UserRole, item_key)
                table.setItem(row_index, 0, item)
            table.setProperty("layer_group_key", group_key)
            table.cellDoubleClicked.connect(partial(self._on_table_double_clicked, table))
            self.layerGroupsTabs.addTab(table, group_title)

    def _on_table_double_clicked(self, table, row: int, column: int) -> None:
        if table is None:
            return
        try:
            item = table.item(row, column)
        except Exception:
            item = None
        if item is None:
            return
        try:
            item_key = item.data(Qt.UserRole)
        except Exception:
            item_key = None
        if not item_key:
            return
        if common.LOG:
            common.log_calls(common.logFile, f"GeoJsonUaDockWidget._on_table_double_clicked(key={item_key!r})")
        try:
            self.request_geojson.emit(str(item_key))
        except Exception:
            return

    def closeEvent(self, event):
        if common.LOG:
            common.log_calls(common.logFile, f"GeoJsonUaDockWidget.closeEvent(event={type(event).__name__})")
        self.closingPlugin.emit()
        event.accept()
