import logging
import os
from qgis.core import (
    QgsScaleBarSettings,
    QgsProject,
    QgsRasterLayer,
    QgsSettings,
    QgsVectorLayer,
    QgsPrintLayout,
    QgsReadWriteContext,
    QgsLayoutItemMap,
    QgsLayoutItemPage,
    QgsUnitTypes,
    QgsLayoutItemLabel,
    QgsLayoutItemPicture,
    QgsLayoutItemLegend,
    QgsLayoutItem,
    QgsLegendStyle,
    QgsLayoutItemScaleBar,
    QgsLayerTreeGroup,
    QgsRectangle,
)
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QColor, QFont
from qgis.PyQt.QtWidgets import (
    QDialog,
    QMessageBox,
    QPushButton,
    QFileDialog,
)
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt import QtGui
from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface
import glob
from .tools.resources import (
    load_ui,
    resources_path,
)
from datetime import date

EDITOR_CLASS = load_ui('CenRa_AutoMap_base.ui')
LOGGER = logging.getLogger('CenRa_AutoMap')
url_osm = 'https://osm.datagrandest.fr/mapcache/?crs=EPSG:2154&featureCount=10&format=image/png&layers=pure&maxHeight=256&maxWidth=256&styles=&url=https://osm.datagrandest.fr/mapcache'
url_ortho = 'http://tiles.craig.fr/ortho/service/?crs=EPSG:2154&featureCount=10&format=image/jpeg&layers=ortho&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/ortho/service'
url_mnt = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=relief&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt'
url_pente = 'http://tiles.craig.fr/mnt/crs=EPSG:2154&featureCount=10&format=image/png&layers=pente&maxHeight=256&maxWidth=256&styles=&url=http://tiles.craig.fr/mnt'
data_source = [
    'CENRA',
    'IGN',
    'CRAIG',
    'OpenStreetMap',
    'Sandre',
    'BRGM',
    'MUSÉUM NATIONAL D’HISTOIRE NATURELLE',
    "Muséum national d'Histoire naturelle",
    'ONF',
    '20xx LPO',
    'ofb.gouv.fr',
    'Stamen Design',
    'MTES',
    'MTES',
    'FEDER',
    'DREAL Auvergne-Rhône-Alpes',
    'INSEE',
    'DGFiP',
    'Fédération des Conservatoires d’espaces naturels',
    'Plan cadastral informatisé - Etalab - juillet 202X',
    'Parcellaire Express - IGN - 202X',
]
A4_size = {'Portrait': {'RIGHT': 210, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 297}, 'Landscape': {'RIGHT': 297, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 210}}
A3_size = {'Portrait': {'RIGHT': 298, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 420}, 'Landscape': {'RIGHT': 420, 'LEFT': 0, 'TOP': 0, 'BOTTOM': 298}}


class AutoMap_Editor(QDialog, EDITOR_CLASS):
    def __init__(self, parent=None):
        _ = parent
        super().__init__()
        self.setupUi(self)
        self.settings = QgsSettings()
        self.s = QSettings()
        self.setWindowIcon(QtGui.QIcon(resources_path('icons', 'icon.png')))

        path = ''
        ix = 0
        plugin_dir = str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
        for i in plugin_dir[1:]:
            ix = ix + 1
            path = path + '/' + i
        # self.tabWidget.setStyleSheet('background-image: url('+path+'/tools/bg/Capture.png);')

        self.verticalScrollBar.hide()
        self.commandLinkButton.clicked.connect(self.chargement_qpt)
        self.radioButton_9.clicked.connect(self.statu_atlas)
        self.radioButton_10.clicked.connect(self.statu_source)
        self.radioButton_11.clicked.connect(self.statu_map)
        self.radioButton_13.clicked.connect(self.statu_titre)
        self.comboBox_2.currentIndexChanged.connect(self.field_list)
        self.comboBox_7.currentIndexChanged.connect(self.update_subtitle)
        self.commandLinkButton_2.clicked.connect(self.load_ortho)
        self.commandLinkButton_3.clicked.connect(self.load_osm)
        self.CustomeLogo.clicked.connect(self.deflogoteck)
        self.verticalScrollBar.valueChanged.connect(self.moveFrame)

        # On ajoute le nom des templates à la liste déroulante de l'onglet "mises en page" :
        mises_en_page = []

        for filename in glob.glob(resources_path("mises_en_pages", "*.py")):
            mises_en_page.append(filename)

        for i, filename in enumerate(mises_en_page):
            nom_fichier = os.path.basename(filename)
            self.comboBox.addItem(nom_fichier)
        self.comboBox.setCurrentIndex(1)

        self.template_parameters = {
            'Carte_size': None,
            'Carte_locals': None,
            'Carte_rotate': None,
            'Carte_frame': None,
            'Carte_2_size': None,
            'Carte_2_locals': None,
            'Carte_2_rotate': None,
            'Legande_size': None,
            'Legande_locals': None,
            'Legande_rotate': None,
            'Legande_frame': None,
            'Arrow_size': None,
            'Arrow_locals': None,
            'Arrow_rotate': None,
            'Arrow_background': None,
            'Arrow_path': None,
            'Echelle_size': None,
            'Echelle_locals': None,
            'Echelle_rotate': None,
            'Logo_size': None,
            'Logo_locals': None,
            'Logo_rotate': None,
            'Titre_size': None,
            'Titre_locals': None,
            'Titre_rotate': None,
            'Sous_titre_size': None,
            'Sous_titre_locals': None,
            'Sous_titre_rotate': None,
            'Credit_size': None,
            'Credit_locals': None,
            'Credit_rotate': None,
            'Credit_alignment': None,
            'Source_size': None,
            'Source_locals': None,
            'Source_rotate': None,
            'Source_alignment': None,
            'Logo_2_size': None,
            'Logo_2_locals': None,
            'Logo_2_rotate': None,
            'Echelle_2_size': None,
            'Echelle_2_locals': None,
            'Echelle_2_rotate': None,
            # Add more variables as needed
        }
        self.update_logo_library()
        self.mComboBox_3.addItems(sorted(data_source))
        self.hide_map()
        self.hide_titre()
        self.hide_source()
        self.hide_atlas()

    def wheelEvent(self, event):
        if (event.angleDelta().y() >= 1):
            vsb = self.verticalScrollBar.value() + 20
        else:
            vsb = self.verticalScrollBar.value() - 20
        self.verticalScrollBar.setValue(vsb)

    def moveFrame(self):
        self.frame.move(self.frame.x(), self.verticalScrollBar.value())

    def update_logo_library(self):
        self.mComboBox_4.clear()
        logo_library = []
        custome_bibliotech = glob.glob(self.s.value("automap/logoteck", 1, type=str) + '*.*')
        for number, logo_x in enumerate(custome_bibliotech):
            logo_library.append(' ' + os.path.basename(logo_x))

        bibliotech = glob.glob(resources_path("logo_library", "*.png"))
        for number, logo_x in enumerate(bibliotech):
            logo_library.append(os.path.basename(logo_x))
        self.mComboBox_4.addItems(sorted(logo_library))

    def select_file(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ShowDirsOnly
        folder = QFileDialog.getExistingDirectory(self, "Sélection du dossier parent", options=options)
        return folder + '/'

    def deflogoteck(self):
        folder = self.select_file()
        logopath = folder
        self.s.setValue("automap/logoteck", str(logopath))
        self.update_logo_library()

    def update_subtitle(self):
        project_subtitle = QgsProject.instance()
        if self.radioButton_13.isChecked() == 1:
            if self.comboBox_7.currentText() != "":
                try:
                    layout_subtitle = project_subtitle.layoutManager().layoutByName(self.comboBox_7.currentText())
                    self.lineEdit_3.setText(layout_subtitle.itemById("SubTitle").text())
                except NameError:
                    print("")

    def load_ortho(self):
        global myGroup, last_group
        runing = False
        try:
            myGroup
        except NameError:
            runing = True
        try:
            last_group
        except NameError:
            last_group = ''
        if runing or (last_group != '' and last_group != 'ortho'):
            layername = False
            layerAll = QgsProject.instance().layerTreeRoot().children()
            xl = 0
            for layeritem in layerAll:
                if layeritem.name() == 'SuperFont':
                    myGroup = layerAll[xl]
                    layername = True
                xl = xl + 1
            if layername:
                (QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup)
                runing = True

        if runing or last_group != 'ortho':

            myGroup = (QgsProject.instance().layerTreeRoot()).addGroup("SuperFont")
            last_group = 'ortho'

            # OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms')
            ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms')
            MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms')
            PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms')

            # OSM_RASTER.loadNamedStyle(resources_path("font", "osm_background.qml"))
            ORTHO_RASTER.loadNamedStyle(resources_path("font", "ortho_aura.qml"))
            MNT_RASTER.loadNamedStyle(resources_path("font", "mnt_alti.qml"))

            # QgsProject.instance().addMapLayer(OSM_RASTER,False)
            QgsProject.instance().addMapLayer(ORTHO_RASTER, False)
            QgsProject.instance().addMapLayer(MNT_RASTER, False)
            QgsProject.instance().addMapLayer(PENTE_RASTER, False)

            # myGroup.addLayer(OSM_RASTER)
            myGroup.addLayer(ORTHO_RASTER)
            myGroup.addLayer(MNT_RASTER)
            myGroup.addLayer(PENTE_RASTER)

    def load_osm(self):
        global myGroup, last_group
        runing = False
        try:
            myGroup
        except NameError:
            runing = True
        try:
            last_group
        except NameError:
            last_group = ''
        if runing or (last_group != '' and last_group != 'osm'):
            layername = False
            layerAll = QgsProject.instance().layerTreeRoot().children()
            xl = 0
            for layeritem in layerAll:
                if layeritem.name() == 'SuperFont':
                    myGroup = layerAll[xl]
                    layername = True
                xl = xl + 1
            if layername:
                (QgsProject.instance().layerTreeRoot()).removeChildNode(myGroup)
                runing = True

        if runing or last_group != 'osm':
            myGroup = (QgsProject.instance().layerTreeRoot()).addGroup("SuperFont")
            last_group = 'osm'

            OSM_RASTER = QgsRasterLayer(url_osm, 'OpenStreetMap Backgound', 'wms')
            # ORTHO_RASTER = QgsRasterLayer(url_ortho, 'Orthophoto AURA', 'wms')
            MNT_RASTER = QgsRasterLayer(url_mnt, 'MNT RGE Alti (<= 1:100000)', 'wms')
            PENTE_RASTER = QgsRasterLayer(url_pente, 'Pente RGE Alti 0 à 90°(<= 1:100000)', 'wms')

            OSM_RASTER.loadNamedStyle(resources_path("font", "osm_background.qml"))
            # ORTHO_RASTER.loadNamedStyle(resources_path("font","ortho_aura.qml"))
            MNT_RASTER.loadNamedStyle(resources_path("font", "mnt_alti.qml"))

            QgsProject.instance().addMapLayer(OSM_RASTER, False)
            # QgsProject.instance().addMapLayer(ORTHO_RASTER,False)
            QgsProject.instance().addMapLayer(MNT_RASTER, False)
            QgsProject.instance().addMapLayer(PENTE_RASTER, False)

            myGroup.addLayer(OSM_RASTER)
            # myGroup.addLayer(ORTHO_RASTER)
            myGroup.addLayer(MNT_RASTER)
            myGroup.addLayer(PENTE_RASTER)

    def raise_(self):
        self.activateWindow()
        self.mComboBox_2.clear()
        self.comboBox_2.clear()
        self.comboBox_3.clear()
        self.comboBox_4.clear()
        self.comboBox_5.clear()
        self.comboBox_6.clear()
        self.comboBox_7.clear()

        if (self.s.value("automap/prenom_nom", "1", type=str) != "1"):
            self.lineEdit_5.setText(self.s.value("automap/prenom_nom", 1, type=str))
        couches = []
        couche_vecteur = ['']
        mapThemes = ['']
        titrePage = ['']
        for lyr in QgsProject.instance().mapLayers().values():
            if isinstance(lyr, QgsVectorLayer):
                couche_vecteur.append(lyr.name())
            couches.append(lyr.name())

        for mapThemesCollection in (QgsProject.instance().mapThemeCollection()).mapThemes():
            mapThemes.append(mapThemesCollection)

        for layoutTitre in (QgsProject.instance().layoutManager().layouts()):
            titrePage.append(layoutTitre.name())

        self.comboBox_2.addItems(sorted(couche_vecteur))
        self.mComboBox_2.addItems(sorted(couches))
        self.comboBox_5.addItems(sorted(mapThemes))
        self.comboBox_6.addItems(sorted(mapThemes))
        self.comboBox_7.addItems(sorted(titrePage))

    def statu_map(self):
        if self.radioButton_11.isChecked() == 1:
            self.show_map()
        else:
            self.hide_map()

    def show_map(self):
        self.groupBox_3.setEnabled(True)
        self.groupBox_3.show()

    def hide_map(self):
        self.groupBox_3.setEnabled(False)
        self.groupBox_3.hide()

    def statu_titre(self):
        if self.radioButton_13.isChecked() == 1:
            self.show_titre()
        else:
            self.hide_titre()

    def show_titre(self):
        self.lineEdit_2.setEnabled(False)
        self.lineEdit_2.hide()
        self.comboBox_7.setEnabled(True)
        self.comboBox_7.show()

    def hide_titre(self):
        self.lineEdit_2.setEnabled(True)
        self.lineEdit_2.show()
        self.comboBox_7.setEnabled(False)
        self.comboBox_7.hide()

    def statu_source(self):
        if self.radioButton_10.isChecked() == 1:
            self.show_source()
        else:
            self.hide_source()

    def show_source(self):
        self.lineEdit_4.setEnabled(False)
        self.lineEdit_4.hide()
        self.mComboBox_3.setEnabled(True)
        self.mComboBox_3.show()

    def hide_source(self):
        self.lineEdit_4.setEnabled(True)
        self.lineEdit_4.show()
        self.mComboBox_3.setEnabled(False)
        self.mComboBox_3.hide()

    def statu_atlas(self):
        if self.radioButton_9.isChecked() == 1:
            self.show_atlas()
        else:
            self.hide_atlas()

    def show_atlas(self):
        self.groupBox.setEnabled(True)
        self.groupBox.show()

    def hide_atlas(self):
        self.groupBox.setEnabled(False)
        self.groupBox.hide()

    def field_list(self):
        fields = []
        self.comboBox_3.clear()
        self.comboBox_4.clear()
        if self.comboBox_2.currentText() != '':
            layer = QgsProject.instance().mapLayersByName(self.comboBox_2.currentText())[0]
            # BUG sur layer.fields() pas défini sur ce qui est pas vecteur
            for vfields in layer.fields():
                fields.append(vfields.name())
            self.comboBox_3.addItems(sorted(fields))
            self.comboBox_4.addItems(sorted(fields))

    def chargement_qpt(self):

        project = QgsProject.instance()
        self.manager = project.layoutManager()
        if self.radioButton_13.isChecked() == 1:
            layout_name = self.comboBox_7.currentText()
        else:
            layout_name = self.lineEdit_2.text()
        # layouts_list = self.manager.printLayouts()

        for filename in glob.glob(resources_path("mises_en_pages", "*.qpt")):
            with open(os.path.join(os.getcwd(), filename), 'r') as f:
                self.layout = QgsPrintLayout(project)
                self.layout.initializeDefaults()
                # myAtlas = self.layout.atlas()
                template_content = f.read()
                doc = QDomDocument()
                doc.setContent(template_content)
                self.layout.loadFromTemplate(doc, QgsReadWriteContext(), True)

                try:
                    cutLayout = layout_name.index("¶")
                except ValueError:
                    cutLayout = 0

                if cutLayout >= 1:
                    self.layout.setName(layout_name)
                    titre_layout_name = layout_name[:cutLayout]
                else:
                    self.layout.setName(layout_name)
                    titre_layout_name = layout_name

                if self.radioButton_6.isChecked() and self.radioButton_7.isChecked():
                    logo_div = A4_size['Portrait']['RIGHT']
                if self.radioButton_6.isChecked() and self.radioButton_8.isChecked():
                    logo_div = A4_size['Portrait']['BOTTOM']
                if self.radioButton_5.isChecked() and self.radioButton_7.isChecked():
                    logo_div = A3_size['Portrait']['RIGHT']
                if self.radioButton_5.isChecked() and self.radioButton_8.isChecked():
                    logo_div = A3_size['Portrait']['BOTTOM']
                # os.path.basename(filename) == "1. Modèle carto standard (consolidé).qpt":
                if True:

                    self.actualisation_mise_en_page()

                    # Add map to layout
                    self.map_modele_test = QgsLayoutItemMap(self.layout)
                    # Charger une carte vide
                    self.map_modele_test.setRect(20, 20, 20, 20)
                    # Mettre le canvas courant comme emprise
                    self.map_modele_test.setExtent(iface.mapCanvas().extent())
                    # Position de la carte dans le composeur

                    self.map_modele_test.setMapRotation(self.template_parameters['Carte_rotate'])
                    self.map_modele_test.attemptResize(self.template_parameters['Carte_size'])
                    self.map_modele_test.attemptMove(self.template_parameters['Carte_locals'])
                    # on dimensionne le rendu de la carte (pour référence la page totale est une page A4 donc 297*210)
                    self.map_modele_test.setKeepLayerSet(True)
                    self.map_modele_test.setKeepLayerStyles(True)
                    if self.radioButton_11.isChecked() == 1:
                        self.map_modele_test.setKeepLayerSet(False)
                        self.map_modele_test.setKeepLayerStyles(False)
                        self.map_modele_test.setFollowVisibilityPreset(True)
                        self.map_modele_test.setFollowVisibilityPresetName(self.comboBox_5.currentText())
                        if self.radioButton_12.isChecked() == 1:
                            self.position_map = QgsLayoutItemMap(self.layout)
                            self.position_map.setRect(20, 20, 20, 20)
                            self.position_map.setExtent(QgsRectangle(618704, 6329245, 1018704, 6649245))
                            # self.position_map.setExtent(QgsRectangle(641552, 6647386, 995856, 6331104))
                            self.position_map.setFollowVisibilityPreset(True)
                            self.position_map.setFollowVisibilityPresetName(self.comboBox_6.currentText())
                            self.position_map.setItemRotation(self.template_parameters['Carte_2_rotate'])
                            self.position_map.attemptResize(self.template_parameters['Carte_2_size'])
                            self.position_map.attemptMove(self.template_parameters['Carte_2_locals'])
                            self.position_map.overview().setLinkedMap(self.map_modele_test)
                            # overviewitem = QgsLayoutItemMapOverviewStack(self.position_map)
                            # map_overview = self.position_map.overview()
                            # map_overview.setLinkedMap(self.map_modele_test)
                            # map_overview.setCentered(True)
                            # overviewitem.addOverview(map_overview)

                            self.position_map.refresh()
                            self.map_modele_test.setFrameEnabled(self.template_parameters['Carte_frame'])
                            self.position_map.setFrameEnabled(self.template_parameters['Carte_2_frame'])
                            self.layout.addLayoutItem(self.position_map)
                            self.position_map.setId("Carte_locals")
                    self.map_modele_test.refresh()

                    self.map_modele_test.setBackgroundColor(QColor(255, 255, 255, 255))
                    self.map_modele_test.setFrameEnabled(self.template_parameters['Carte_frame'])
                    if self.radioButton_9.isChecked() == 1:
                        self.map_modele_test.setAtlasDriven(True)
                    self.layout.addLayoutItem(self.map_modele_test)
                    self.map_modele_test.setId("carte_principale")

                    # Ajout d'un titre à la mise en page
                    title = QgsLayoutItemLabel(self.layout)
                    self.layout.addLayoutItem(title)
                    titre = titre_layout_name
                    title.setText(titre)
                    Font = QFont("Calibri", 15, False)
                    Font.setBold(True)
                    title.setFont(Font)
                    title.setItemRotation(self.template_parameters['Titre_rotate'])
                    title.attemptResize(self.template_parameters['Titre_size'])
                    title.attemptMove(self.template_parameters['Titre_locals'])

                    title.setBackgroundEnabled(True)
                    title.setBackgroundColor(QColor(255, 255, 255, 130))
                    self.layout.addItem(title)
                    # title.adjustSizeToText() on n'utilise plutot setFixedSize pour pouvoir centrer le titre de manière plus optimale ici
                    title.setHAlign(Qt.AlignmentFlag(0x0004))
                    title.setVAlign(Qt.AlignmentFlag(0x0080))

                    # Ajout d'un sous titre à la mise en page
                    subtitle = QgsLayoutItemLabel(self.layout)
                    self.layout.addLayoutItem(subtitle)
                    titre = self.lineEdit_3.text()
                    if self.radioButton_9.isChecked() == 1:
                        titre = titre + ' [%' + self.comboBox_4.currentText() + '%]'
                    subtitle.setText(titre)
                    subtitle.setFont(QFont("Calibri", 10))
                    subtitle.setItemRotation(self.template_parameters['Sous_titre_rotate'])
                    subtitle.attemptResize(self.template_parameters['Sous_titre_size'])
                    subtitle.attemptMove(self.template_parameters['Sous_titre_locals'])
                    subtitle.setId("SubTitle")
                    subtitle.setBackgroundEnabled(True)
                    subtitle.setBackgroundColor(QColor(255, 255, 255, 130))
                    self.layout.addItem(subtitle)
                    subtitle.setHAlign(Qt.AlignmentFlag(0x0004))
                    subtitle.setVAlign(Qt.AlignmentFlag(0x0080))

                    # Ajout du logo CEN NA en haut à gauche de la page
                    logo = QgsLayoutItemPicture(self.layout)
                    logo.setResizeMode(QgsLayoutItemPicture.Zoom)
                    logo.setPictureAnchor(QgsLayoutItem.ReferencePoint(4))
                    logo.setMode(QgsLayoutItemPicture.FormatRaster)
                    logo.setItemRotation(self.template_parameters['Logo_rotate'])
                    logo.setFixedSize(self.template_parameters['Logo_size'])
                    logo.attemptMove(self.template_parameters['Logo_locals'])
                    logo.setPicturePath(resources_path("icons", "CEN_RA.png"))
                    logo.setId('logo')
                    self.layout.addLayoutItem(logo)

                    # Ajout de la legende :
                    legend = QgsLayoutItemLegend(self.layout)

                    legend.setId('legende_model1')
                    # legend.setTitle('Legende')
                    legend.adjustBoxSize()
                    legend.setFrameEnabled(self.template_parameters['Legande_frame'])
                    legend.setAutoUpdateModel(False)

                    legend.setLinkedMap(self.map_modele_test)

                    checked_items = self.mComboBox_2.checkedItems()
                    self.layout.addItem(legend)

                    # group_name = 'Périmètres écologiques'  # Name of a group in your legend

                    layers_to_remove = []

                    for lyr in project.mapLayers().values():
                        if lyr.name() not in checked_items:
                            layers_to_remove.append(lyr.name())

                    # the layer tree
                    root = project.layerTreeRoot()

                    # get legend
                    legend = [i for i in self.layout.items() if isinstance(i, QgsLayoutItemLegend)][0]

                    # disable auto-update
                    legend.setAutoUpdateModel(False)
                    legend.setLegendFilterByMapEnabled(True)
                    # legend model
                    model = legend.model()

                    # the root legend group
                    root_group = model.rootGroup()

                    # loop through layer names
                    for layer_name in layers_to_remove:
                        # find layer in project
                        layer = project.mapLayersByName(layer_name)[0]
                        # get layer tree layer instance of layer
                        layertreelayer = root.findLayer(layer.id())

                        # get the parent of the layer tree layer (layer tree root, or group)
                        if layertreelayer is not None:
                            parent = layertreelayer.parent()

                        # if the parent is a group and has a name, find it and remove the layer
                        if isinstance(parent, QgsLayerTreeGroup) and parent.name():
                            group = root_group.findGroup(parent.name())
                            group.removeLayer(layer)
                        # remove layers that are not in a group
                        else:
                            root_group.removeLayer(layer)

                legend.setEqualColumnWidth(True)
                legend.setSplitLayer(True)
                legend.setColumnSpace(5)
                legend.rstyle(QgsLegendStyle.Title).setMargin(1.5)  # 1 mm
                legend.rstyle(QgsLegendStyle.Group).setMargin(QgsLegendStyle.Top, 3)
                legend.rstyle(QgsLegendStyle.Subgroup).setMargin(QgsLegendStyle.Top, 3)
                legend.setColumnCount(self.spinBox.value())
                legend.setItemRotation(self.template_parameters['Legande_rotate'])

                legend.adjustBoxSize()
                legend.setBackgroundEnabled(True)
                legend.setBackgroundColor(QColor(255, 255, 255, 130))
                self.layout.refresh()

                legend.updateLegend()
                legend.attemptMove(self.template_parameters['Legande_locals'])

                # Ajout de l'échelle numeric à la mise en page
                self.scalebarnumeric_qpt = QgsLayoutItemScaleBar(self.layout)
                self.scalebarnumeric_qpt.setStyle('Numeric')
                self.scalebarnumeric_qpt.setLinkedMap(self.map_modele_test)
                self.scalebarnumeric_qpt.applyDefaultSize()
#                self.scalebarnumeric_qpt.applyDefaultSettings()

                self.scalebarnumeric_qpt.setNumberOfSegments(2)
                self.scalebarnumeric_qpt.setNumberOfSegmentsLeft(0)

                self.scalebarnumeric_qpt.setFont(QFont("Calibri", 12))
                self.scalebarnumeric_qpt.setItemRotation(self.template_parameters['Echelle_rotate'])
                self.scalebarnumeric_qpt.attemptMove(self.template_parameters['Echelle_locals'])
                self.scalebarnumeric_qpt.attemptResize(self.template_parameters['Echelle_size'])
                self.scalebarnumeric_qpt.setAlignment(QgsScaleBarSettings.Alignment(1))
                self.scalebarnumeric_qpt.setBackgroundEnabled(True)
                self.scalebarnumeric_qpt.setBackgroundColor(QColor(255, 255, 255, 130))

                self.layout.addLayoutItem(self.scalebarnumeric_qpt)

                # Ajout de l'échelle à la mise en page
                self.scalebar_qpt = QgsLayoutItemScaleBar(self.layout)
                self.scalebar_qpt.setStyle('Single Box')
                self.scalebar_qpt.setLinkedMap(self.map_modele_test)
                self.scalebar_qpt.setFillColor(QColor(144, 144, 144, 255))
                self.scalebar_qpt.applyDefaultSize()
                self.scalebar_qpt.applyDefaultSettings()

                self.scalebar_qpt.setNumberOfSegments(2)
                self.scalebar_qpt.setNumberOfSegmentsLeft(0)

                self.scalebar_qpt.setFont(QFont("Calibri", 12))
                self.scalebar_qpt.setItemRotation(self.template_parameters['Echelle_2_rotate'])
                self.scalebar_qpt.attemptMove(self.template_parameters['Echelle_2_locals'])
                self.scalebar_qpt.attemptResize(self.template_parameters['Echelle_2_size'])
                self.scalebar_qpt.setAlignment(QgsScaleBarSettings.Alignment(1))
                self.scalebar_qpt.setBackgroundEnabled(True)
                self.scalebar_qpt.setBackgroundColor(QColor(255, 255, 255, 130))

                self.layout.addLayoutItem(self.scalebar_qpt)
                # self.scalebar_qpt.setFixedSize(QgsLayoutSize(55, 15))

                # ajout de la fleche du Nord
                north = QgsLayoutItemPicture(self.layout)
                north.setPicturePath(resources_path("mises_en_pages", self.template_parameters['Arrow_path']))
                north.setLinkedMap(self.map_modele_test)
                self.layout.addLayoutItem(north)
                north.setPictureAnchor(QgsLayoutItem.ReferencePoint(4))
                north.setItemRotation(self.template_parameters['Arrow_rotate'])
                north.attemptMove(self.template_parameters['Arrow_locals'])
                north.attemptResize(self.template_parameters['Arrow_size'])
                north.setSvgStrokeColor(QColor(255, 255, 255, 255))
                north.setSvgFillColor(QColor(76, 76, 76, 255))
                north.setBackgroundEnabled(self.template_parameters['Arrow_background'])
                north.setBackgroundColor(QColor(255, 255, 255, 130))

                if self.radioButton_10.isChecked() == 1:
                    text_source = ' '
                    for Item_mComboBox_3 in self.mComboBox_3.checkedItems():
                        text_source = text_source + Item_mComboBox_3 + ','
                    text_source = text_source[:-1]
                    info_text = ["Source :" + text_source][0]
                else:
                    info_text = ["Source : " + self.lineEdit_4.text()][0]
                # ajout note info:
                if self.radioButton_14.isChecked() == 1:
                    self.s.setValue("automap/prenom_nom", self.lineEdit_5.text())
                    prenom_nom = self.s.value("automap/prenom_nom", 1, type=str)
                    info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ") par " + prenom_nom]
                else:
                    info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime("%d/%m/%Y") + ")"]
                credit_text = QgsLayoutItemLabel(self.layout)
                credit_text.setText(info[0])
                credit_text.setFont(QFont("Calibri", 9))
                credit_text.setHAlign(Qt.AlignmentFlag(self.template_parameters['Credit_alignment']))
                credit_text.setVAlign(Qt.AlignmentFlag(0x0080))
                credit_text.setMarginX(2)
                credit_text.setBackgroundEnabled(True)
                credit_text.setBackgroundColor(QColor(255, 255, 255, 130))
                credit_text2 = QgsLayoutItemLabel(self.layout)
                credit_text2.setText(info_text)
                credit_text2.setFont(QFont("Calibri", 9))
                credit_text2.setHAlign(Qt.AlignmentFlag(self.template_parameters['Source_alignment']))
                credit_text2.setVAlign(Qt.AlignmentFlag(0x0080))
                credit_text2.setMarginX(2)
                credit_text.setItemRotation(self.template_parameters['Credit_rotate'])
                credit_text.attemptResize(self.template_parameters['Credit_size'])
                credit_text.attemptMove(self.template_parameters['Credit_locals'])
                credit_text2.setItemRotation(self.template_parameters['Source_rotate'])
                credit_text2.attemptResize(self.template_parameters['Source_size'])
                credit_text2.attemptMove(self.template_parameters['Source_locals'])
                credit_text2.setBackgroundEnabled(True)
                credit_text2.setBackgroundColor(QColor(255, 255, 255, 130))
                self.layout.addLayoutItem(credit_text)
                self.layout.addLayoutItem(credit_text2)

                # Ajout du logo credit en bas à droit de la page
                len_item = (len(self.mComboBox_4.checkedItems()))
                for logo_run in self.mComboBox_4.checkedItems():
                    logo_credit = QgsLayoutItemPicture(self.layout)
                    logo_credit.setResizeMode(QgsLayoutItemPicture.Zoom)
                    logo_credit.setPictureAnchor(QgsLayoutItem.ReferencePoint(4))
                    logo_credit.setMode(QgsLayoutItemPicture.FormatRaster)
                    cur_x = self.template_parameters['Logo_2_locals'].x()
                    logo_credit.setItemRotation(self.template_parameters['Logo_2_rotate'])
                    logo_credit.attemptMove(self.template_parameters['Logo_2_locals'])
                    self.template_parameters['Logo_2_locals'].setX(cur_x + (logo_div / len_item))
                    logo_credit.setFixedSize(self.template_parameters['Logo_2_size'])
                    if logo_run[0] == ' ':
                        logo_credit.setPicturePath(self.s.value("automap/logoteck", 1, type=str) + logo_run[1:])
                    else:
                        logo_credit.setPicturePath(resources_path("logo_library", logo_run))
                    logo_credit.setId('logo_' + logo_run)
                    logo_credit.setBackgroundEnabled(True)
                    logo_credit.setBackgroundColor(QColor(255, 255, 255, 130))
                    self.layout.addLayoutItem(logo_credit)

                # credit_text.attemptResize(QgsLayoutSize(95, 5, QgsUnitTypes.LayoutMillimeters))

                self.bar_echelle_auto(iface.mapCanvas(), self.scalebar_qpt)

                existing_layout = project.layoutManager().layoutByName(self.layout.name())
            if existing_layout:
                self.QMBquestion = QMessageBox()
                self.QMBquestion.setWindowTitle(u"Attention !")
                self.QMBquestion.setIcon(QMessageBox.Icon.Warning)
                self.QMBquestion.setText("Mise en page existante, la mise en page va être écrasée !")
                self.QMBquestion.setStandardButtons(QMessageBox.StandardButton(0x00004000) | QMessageBox.StandardButton(0x00010000))
                self.QMBquestion.addButton(QPushButton('Autre mise en page'), QMessageBox.ButtonRole(0))
                self.QMBquestion = self.QMBquestion.exec()

                # if self.radioButton_12.isChecked() != 1:
                if self.QMBquestion == QMessageBox.StandardButton(0x00004000):
                    project.layoutManager().removeLayout(existing_layout)
                    # result = project.layoutManager().addLayout(self.layout)
                elif self.QMBquestion != QMessageBox.StandardButton(0x00010000):
                    LayoutCOUNT = 0
                    arrayManager = []
                    for AddArrayManager in project.layoutManager().layouts():
                        arrayManager.append(AddArrayManager.name())
                    arrayManager.sort()
                    for LayoutNAME in arrayManager:
                        if LayoutNAME == layout_name:
                            LayoutCOUNT = LayoutCOUNT + 1
                        if LayoutNAME == layout_name + "¶" + str(LayoutCOUNT):
                            LayoutCOUNT = LayoutCOUNT + 1
                    layout_name = (layout_name + "¶" + str(LayoutCOUNT))
                    self.layout.setName(layout_name)

            else:
                existing_layout = True

        self.manager.addLayout(self.layout)
        if self.radioButton_9.isChecked() == 1:
            self.layout.atlas().setEnabled(True)
            cover_layer = QgsProject.instance().mapLayersByName(self.comboBox_2.currentText())[0]
            self.layout.atlas().setCoverageLayer(cover_layer)
            self.layout.atlas().setPageNameExpression(self.comboBox_4.currentText())

        fichier_mise_en_page = layout_name
        layout_modifie = QgsProject.instance().layoutManager().layoutByName(fichier_mise_en_page)
        try:
            if (self.QMBquestion == QMessageBox.AcceptRole):
                TryMessage = (self.QMBquestion == QMessageBox.AcceptRole)
            elif (self.QMBquestion == QMessageBox.Yes):
                TryMessage = (self.QMBquestion == QMessageBox.Yes)
            else:
                TryMessage = False
            del self.QMBquestion
        except ValueError:
            TryMessage = True
        except AttributeError:
            TryMessage = True

        if TryMessage is True:
            iface.openLayoutDesigner(layout_modifie)
            self.close()
        else:
            self.activateWindow()

    def actualisation_mise_en_page(self):
        values_page = self.comboBox.currentText()

        if self.radioButton_6.isChecked() and self.radioButton_7.isChecked():
            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A4', QgsLayoutItemPage.Portrait)

        if self.radioButton_6.isChecked() and self.radioButton_8.isChecked():
            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A4', QgsLayoutItemPage.Landscape)

        if self.radioButton_5.isChecked() and self.radioButton_7.isChecked():
            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A3', QgsLayoutItemPage.Portrait)

        if self.radioButton_5.isChecked() and self.radioButton_8.isChecked():
            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A3', QgsLayoutItemPage.Landscape)

        values_page_import = values_page[:-3]
        eval("exec('from .tools.mises_en_pages import ' + values_page_import)")
        eval("exec('self.template_parameters = '+ values_page_import + '.fletch_canvas(self)')")

    def bar_echelle_auto(self, echelle, bar_echelle):
        if True:
            if echelle.scale() >= 40000:
                bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers)
                bar_echelle.setUnitLabel("km")
                bar_echelle.setUnitsPerSegment(round((echelle.scale() * 0.04) / 1000))
            else:
                bar_echelle.setUnits(QgsUnitTypes.DistanceMeters)
                bar_echelle.setUnitLabel("m")
                bar_echelle.setUnitsPerSegment(round(echelle.scale() * 0.04))

        bar_echelle.update()
