# -*- coding: utf-8 -*-
"""
/***************************************************************************
 StyleApplicatorDockWidget
                                 A QGIS plugin
 A plugin to help develop Material Take-Offs and Equipment Lists for pipeline projects.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2025-11-01
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Thomas Raj
        email                : t.suraj.raj@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 os

from qgis.utils import iface

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

from qgis.core import QgsMapLayerProxyModel, QgsProject, QgsField, QgsVectorLayer, QgsEditorWidgetSetup, QgsDefaultValue, QgsMapLayer

from PyQt5.QtWidgets import QTreeWidgetItem, QListWidget, QMessageBox
from qgis.PyQt.QtCore import Qt, QVariant

from qgis.gui import QgsFileWidget

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


class StyleApplicatorDockWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor."""
        super(StyleApplicatorDockWidget, self).__init__(parent)
        # 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)
        
        self.populate_qml_list()
        
        self.fwQMLFolderPath.setStorageMode(QgsFileWidget.GetDirectory)
        
        script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        default_path = os.path.join(script_dir,'layer_styles')

        self.fwQMLFolderPath.setFilePath(default_path)
        self.populate_qml_list()
        self.fwQMLFolderPath.fileChanged.connect(self.populate_qml_list)
        
        self.pbApplyStyle.clicked.connect(self.apply_style_to_layer)
        
    def populate_qml_list(self):
        self.listWidget.clear()

        folder_path = self.fwQMLFolderPath.filePath()

        if not os.path.isdir(folder_path):
            return

        qml_files = sorted(
            f for f in os.listdir(folder_path)
            if f.lower().endswith(".qml")
        )
        
        self.listWidget.addItems(qml_files)

    def apply_style_to_layer(self):
        
        style = self.listWidget.currentItem().text()
        folder_path = self.fwQMLFolderPath.filePath()
        style_path = os.path.join(folder_path,style)
    
        def re_calc_graduated(layer, qml_path):
            layer.loadNamedStyle(qml_path)
            renderer = layer.renderer()

            if renderer.type() == 'graduatedSymbol':
                field_name = renderer.classAttribute()
                attr_index = layer.fields().indexOf(field_name)

                # Most builds (like yours) want both layer and field index
                try:
                    renderer.updateClasses(layer, attr_index)
                except TypeError:
                    # fallback for older versions that expect field name instead
                    renderer.updateClasses(layer, field_name)

                # Reapply and refresh
                layer.setRenderer(renderer)
                layer.triggerRepaint()
    
        
        layer = iface.activeLayer()
        
        try:
            re_calc_graduated(layer=layer, qml_path=style_path)
        
        except:
            QMessageBox.warning(self, "Warning", "Style geometry does not match layer geometry.")
        
        print(style_path)
        print(layer.name())

    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()
