# -*- coding: utf-8 -*-
"""
/***************************************************************************
 MirGradDTPDialog
                                 A QGIS plugin
 Набор инструментов для работы с материалами документации территориального планирования
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2024-03-18
        git sha              : $Format:%H$
        copyright            : (C) 2024 by I.Bukharin/Mirproekt
        email                : iabukharin@gmail.com
 ***************************************************************************/
"""

import os
from os.path import isfile, isdir

from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from qgis.core import Qgis, QgsFieldProxyModel, QgsExpressionContextUtils, QgsProject, QgsVectorLayer
from PyQt5.QtWidgets import QDialogButtonBox

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


class MirGradDTPDialogCoord(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(MirGradDTPDialogCoord, 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._initMapLayerComboBox()
        self._initVidPerechnia()
        self._initFormatResult()

        self.mFieldExpressionWidget_2.setFilters(QgsFieldProxyModel.Filter.Int | QgsFieldProxyModel.Filter.String)
        self.mFieldExpressionWidget.setFilters(QgsFieldProxyModel.Filter.Int | QgsFieldProxyModel.Filter.String)
        self.mFieldExpressionWidget.fieldChanged.connect(self.nameObjChanged)
        

        
        #print(self.mMapLayerComboBox.filters())
        #self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
        #self.mQgsFileWidget.fileChanged.connect(self.selectFileChanged)
        #self.checkBox_2.stateChanged.connect(self.pathComboBoxChaged)
    
    def selectedFormatChanged(self, curIndx):
        if curIndx == 0:
            self.mQgsFileWidget.setEnabled(False)
            pass
        elif curIndx == 1:
            self.mQgsFileWidget.setEnabled(True)
            self.mQgsFileWidget.setStorageMode(1)
            pass
        elif curIndx == 2:
            self.mQgsFileWidget.setEnabled(True)
            self.mQgsFileWidget.setStorageMode(1)
            pass
        return

    def _initFormatResult(self):
        self.comboBox_2.addItem('В буфер обмена')
        self.comboBox_2.addItem('Отдельный файл для каждого объекта')
        self.comboBox_2.addItem('Единый файл для всех объектов')
        self.comboBox_2.currentIndexChanged.connect(self.selectedFormatChanged)
        self.comboBox_2.currentIndexChanged.emit( self.comboBox_2.currentIndex())
        return

    def selectedVidChanged(self, curIndx):
        if curIndx == 0:
            self.lineEdit.setEnabled(False)
            self.mFieldExpressionWidget_2.setEnabled(False)
            self.lineEdit_2.setEnabled(False)
        else:
            self.lineEdit.setEnabled(True)
            self.mFieldExpressionWidget_2.setEnabled(True)
            self.lineEdit_2.setEnabled(True)
        return
    
    def _initVidPerechnia(self):
        self.comboBox.addItem('Таблица перечня координат')
        self.comboBox.addItem('Графическое описание границ ...')
        self.comboBox.currentIndexChanged.connect(self.selectedVidChanged)
        self.comboBox.currentIndexChanged.emit( self.comboBox.currentIndex())
        return

    def _initMapLayerComboBox(self):
        # Блокируем сигналы на время настройки, чтобы избежать лишних срабатываний
        self.mMapLayerComboBox.blockSignals(True)
        
        # Устанавливаем фильтры типов геометрии
        self.mMapLayerComboBox.setFilters(Qgis.LayerFilter.LineLayer | Qgis.LayerFilter.PolygonLayer)
        self.mMapLayerComboBox.setAllowEmptyLayer(False)
        
        # Собираем слои для исключения (пустые слои)
        # Используем менеджер проекта напрямую, это надежнее
        excludeLayersList = []
        for layer in QgsProject.instance().mapLayers().values():
            # Проверяем, что слой векторный
            if isinstance(layer, QgsVectorLayer):
                if layer.featureCount() < 1:
                    excludeLayersList.append(layer)
            else:
                # Если это растр или другой тип, тоже исключаем его из обработки
                excludeLayersList.append(layer)
        self.mMapLayerComboBox.setExceptedLayerList(excludeLayersList)
        
        self.mMapLayerComboBox.blockSignals(False)
        
        # Подключаем сигнал (только один раз)
        # Используем context manager или проверку, чтобы не плодить подключения
        try:
            self.mMapLayerComboBox.layerChanged.disconnect(self.selectedLayerChanged)
        except TypeError:
            pass
        self.mMapLayerComboBox.layerChanged.connect(self.selectedLayerChanged)

        # Вместо emit вручную вызываем обработчик для текущего слоя
        if self.mMapLayerComboBox.currentLayer():
            self.selectedLayerChanged(self.mMapLayerComboBox.currentLayer())

    def nameObjChanged(self, fieldName):
        #print('fieldName: ', fieldName)
        #print('allowEmptyFieldName: ', self.mFieldExpressionWidget.allowEmptyFieldName())
        #print('allowEvalErrors: ', self.mFieldExpressionWidget.allowEvalErrors())
        """ objNameExpression = self.mFieldExpressionWidget.asExpression()
        objNameExpression = QgsExpression(objNameExpression)
        context = QgsExpressionContext()
        context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(self.mMapLayerComboBox.currentLayer()))
        for feat in self.mMapLayerComboBox.currentLayer().getFeatures():
            context.setFeature(feat)
            print(objNameExpression.evaluate(context))
            break """
        #self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(self.mFieldExpressionWidget.isExpressionValid(fieldName))
        return

    def selectedLayerChanged(self, layer):
        if layer is None:
            return
        if layer.selectedFeatureCount() > 0:
            self.checkBox.setEnabled(True)
            self.checkBox.setChecked(True)
        else:
            self.checkBox.setChecked(False)
            self.checkBox.setEnabled(False)
            
        self.mFieldExpressionWidget.setLayer(layer)
        self.mFieldExpressionWidget_2.setLayer(layer)
        self.mFieldExpressionWidget.appendScope(QgsExpressionContextUtils.layerScope(layer))
        self.mFieldExpressionWidget_2.appendScope(QgsExpressionContextUtils.layerScope(layer))
        #print(layer.name())
        return

    """ def selectFileChanged(self, QString):
        button = self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok)
        if isdir(QString):
            button.setEnabled(True)
        else:
            button.setEnabled(False)
    
    def pathComboBoxChaged(self, state):
        self.mQgsFileWidget.setEnabled(state)
        button = self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok)
        if not state:
            button.setEnabled(True)
        else:
            self.selectFileChanged(self.mQgsFileWidget.filePath()) """
            