## Fichier de traitement de la compatibilité QT5 et QT6

# compat_qt.py
"""
Fichier de compatibilité Qt5 / Qt6 pour QGIS.
Permet de centraliser les différences entre Qt5 et Qt6.
"""

from qgis.PyQt import QtCore, QtGui, QtWidgets
from qgis.PyQt.QtWidgets import QDialog, QMessageBox
from qgis.core import QgsVectorLayer


# ---------------------------
# Détection Qt6 / Qt5
# ---------------------------
IS_QT6 = hasattr(QtCore.Qt, 'ItemFlag')

# ---------------------------
# Constantes Qt pour QTableWidget, QComboBox, etc.
# ---------------------------
if IS_QT6:
    # Qt6
    ItemIsEditable = QtCore.Qt.ItemFlag.ItemIsEditable
    MatchFixedString = QtCore.Qt.MatchFlag.MatchFixedString
    HeaderStretch = QtWidgets.QHeaderView.ResizeMode.Stretch
    WindowModal = QtCore.Qt.WindowModality.WindowModal
    LeftButton = QtCore.Qt.MouseButton.LeftButton
    RightButton = QtCore.Qt.MouseButton.RightButton
    ColorRed = QtGui.QColor(QtCore.Qt.GlobalColor.red)
    Key_Return = QtCore.Qt.Key.Key_Return
    Key_Enter = QtCore.Qt.Key.Key_Enter
    Key_Escape = QtCore.Qt.Key.Key_Escape
    CrossCursor = QtCore.Qt.CursorShape.CrossCursor
    ArrowCursor = QtCore.Qt.CursorShape.ArrowCursor

    # QMessageBox
    MB_Yes = getattr(QMessageBox.StandardButton, 'Yes', None)
    MB_No = getattr(QMessageBox.StandardButton, 'No', None)
    MB_Ok = getattr(QMessageBox.StandardButton, 'Ok', None)
    # fallback si absent
    if MB_Yes is None: MB_Yes = QMessageBox.Yes
    if MB_No is None: MB_No = QMessageBox.No
    if MB_Ok is None: MB_Ok = QMessageBox.Ok

else:
    # Qt5
    ItemIsEditable = QtCore.Qt.ItemIsEditable
    MatchFixedString = QtCore.Qt.MatchFixedString
    HeaderStretch = QtWidgets.QHeaderView.Stretch
    WindowModal = QtCore.Qt.WindowModality.WindowModal
    LeftButton = QtCore.Qt.LeftButton
    RightButton = QtCore.Qt.RightButton
    ColorRed = QtGui.QColor(QtCore.Qt.red)
    Key_Return = QtCore.Qt.Key_Return
    Key_Enter = QtCore.Qt.Key_Enter
    Key_Escape = QtCore.Qt.Key_Escape
    CrossCursor = QtCore.Qt.CrossCursor
    ArrowCursor = QtCore.Qt.ArrowCursor

    MB_Yes = QMessageBox.Yes
    MB_No = QMessageBox.No
    MB_Ok = QMessageBox.Ok


# ---------------------------
# Fonction d'exécution QDialog (Qt5 / Qt6)
# ---------------------------
def exec_dialog(dlg: QDialog):
    """
    Exécute une boîte de dialogue et retourne le résultat.
    Compatible PyQt5 (exec_) et PyQt6 (exec).
    """
    try:
        return dlg.exec()    # Qt6
    except AttributeError:
        return dlg.exec_()   # Qt5


# ---------------------------
# WindowFlags (Qt5 / Qt6)
# ---------------------------
if IS_QT6:
    Window = QtCore.Qt.WindowType.Window
    Dialog = QtCore.Qt.WindowType.Dialog
    Tool = QtCore.Qt.WindowType.Tool
else:
    Window = QtCore.Qt.Window
    Dialog = QtCore.Qt.Dialog
    Tool = QtCore.Qt.Tool




# ---------------------------
# Types pour QgsField
# ---------------------------
# Compatibilité QVariant Qt5 / Qt6
try:
    # Qt5 : QVariant existe
    from qgis.PyQt.QtCore import QVariant
except ImportError:
    # Qt6 : QVariant n'existe plus, on remplace par les types Python natifs
    class QVariant:
        String = str
        Int = int
        LongLong = int
        Double = float
        Bool = bool
        Date = QtCore.QDate

def disable_native_form(layer):
    """
    Désactive le formulaire d'attributs natif QGIS lors de la création d'entités.
    Compatible QGIS 3.36 → 4.0 (Qt6)
    """
    if not isinstance(layer, QgsVectorLayer):
        return

    # QGIS 4 (Qt6)
    if hasattr(layer, "setFeatureFormSuppress"):
        layer.setFeatureFormSuppress(QgsVectorLayer.FeatureFormSuppress.SuppressOnCreate)
    else:
        # QGIS 3.x
        cfg = layer.editFormConfig()
        if hasattr(cfg, "setSuppressForm"):
            cfg.setSuppressForm(True)


# Mapping type générique pour QgsField
TYPE_MAPPING = {
    "String": QVariant.String,
    "Integer": QVariant.Int,
    "Integer64": QVariant.LongLong,
    "Real": QVariant.Double,
    "Boolean": QVariant.Bool,
    "Date": QVariant.Date,
}


# ---------------------------
# Fonctions utilitaires
# ---------------------------

def to_qvariant(value, champ_type):
    """
    Convertir une valeur en type compatible QgsField selon Qt6/Qt5.
    """
    if champ_type in (int, "Integer", "Integer64"):
        return int(value) if value is not None else 0
    elif champ_type in (float, "Real"):
        return float(value) if value is not None else 0.0
    elif champ_type in (str, "String"):
        return str(value) if value is not None else ""
    elif champ_type == bool:
        return bool(value)
    elif champ_type == QtCore.QDate:
        return value if isinstance(value, QtCore.QDate) else QtCore.QDate()
    else:
        return value
