import logging
import os

from collections import namedtuple
from enum import Enum
from functools import partial
from pathlib import Path
from xml.dom.minidom import parseString
from qgis.gui import *
from qgis.core import (
    NULL,
    QgsApplication,
    QgsDataSourceUri,
    QgsProject,
    QgsProviderConnectionException,
    QgsProviderRegistry,
    QgsRasterLayer,
    QgsSettings,
    QgsVectorLayer,
    QgsGeometry,
    QgsPrintLayout,
    QgsReadWriteContext,
    QgsLayoutItemMap,
    QgsLayoutItemPage,
    QgsLayoutSize,
    QgsUnitTypes,
    QgsLayoutPoint,
    QgsLayoutItemLabel,
    QgsLayoutItemPicture,
    QgsLayoutItemLegend,
    QgsLegendStyle,
    QgsLayoutItemScaleBar,
    QgsLayerTreeGroup,
    QgsCoordinateReferenceSystem,
    QgsCoordinateTransform,
    QgsLayerTree,
)

from qgis.PyQt.QtCore import QLocale, QUrl, QDateTime, Qt
from qgis.PyQt.QtGui import QDesktopServices, QIcon, QColor, QFont, QMovie
from qgis.PyQt.QtPrintSupport import QPrinter
from qgis.PyQt.QtWebKitWidgets import QWebPage
from qgis.PyQt.QtWidgets import (
    QDialog,
    QAction,
    QDockWidget,
    QFileDialog,
    QInputDialog,
    QMenu,
    QToolButton,
    QTableWidget, 
    QTableWidgetItem,
)
from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface
import glob
from .tools.resources import (
    load_ui,
    resources_path,
    login_base,
    send_issues,
)
from .issues import CenRa_Issues
from datetime import date

EDITOR_CLASS = load_ui('CenRa_AutoMap_base.ui')
LOGGER = logging.getLogger('CenRa_AutoMap')

class AutoMap_Editor(QDialog, EDITOR_CLASS):

    def __init__(self, parent=None):
        _ = parent
        super().__init__()
        self.setupUi(self)
        self.settings = QgsSettings()

        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.commandLinkButton.clicked.connect(self.chargement_qpt)

        ## 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","*.qpt")):
            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 = {
            'map_size': None,
            'map_position' : None,
            'title_position': None,
            'title_size': None,
            'subtitle_position': None,
            'subtitle_size': None,
            'logo_position': None,
            'logo_size': None,
            'legend_position': None,
            'legend_size': None,
            'scalebarnumeric_position':None,
            'scalebarnumeric_size':None,
            'scalebar_position': None,
            'scalebar_size': None,
            'north_position': None,
            'north_size': None,
            'credit_text_position': None,
            'credit_text_size': None,
            'credit_text2_position': None,
            'credit_text2_size': None,
            # Add more variables as needed
        }
    def raise_(self):
        self.mComboBox_2.clear()

        couches = []
        for lyr in QgsProject.instance().mapLayers().values():
            couches.append(lyr.name())

        self.mComboBox_2.addItems(sorted(couches))

    def chargement_qpt(self):


        project = QgsProject.instance()
        self.manager = project.layoutManager()
        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()
                template_content = f.read()
                doc = QDomDocument()
                doc.setContent(template_content)
                self.layout.loadFromTemplate(doc, QgsReadWriteContext(), True)
                self.layout.setName(self.lineEdit_2.text())

                if os.path.basename(filename) == "1. Modèle carto standard (consolidé).qpt":

                    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.attemptMove(self.template_parameters['map_position'])
                    # 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.attemptResize(self.template_parameters['map_size'])
                    self.map_modele_test.refresh()
                    self.map_modele_test.setKeepLayerSet(True)
                    self.map_modele_test.setKeepLayerStyles(True)

                    self.map_modele_test.setBackgroundColor(QColor(255, 255, 255, 255))
                    self.map_modele_test.setFrameEnabled(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 = self.lineEdit_2.text()
                    title.setText(titre)
                    title.setFont(QFont("Calibri", 15, QFont.Bold))
                    title.attemptMove(self.template_parameters['title_position'])
                    title.attemptResize(self.template_parameters['title_size'])
                    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.AlignHCenter)
                    title.setVAlign(Qt.AlignVCenter)


                    ## Ajout d'un sous titre à la mise en page
                    subtitle = QgsLayoutItemLabel(self.layout)
                    self.layout.addLayoutItem(subtitle)
                    titre = self.lineEdit_3.text()
                    subtitle.setText(titre)
                    subtitle.setFont(QFont("MS Shell Dlg 2", 10))
                    subtitle.attemptMove(self.template_parameters['subtitle_position'])
                    subtitle.attemptResize(self.template_parameters['subtitle_size'])
                    self.layout.addItem(subtitle)
                    subtitle.setHAlign(Qt.AlignHCenter)
                    subtitle.setVAlign(Qt.AlignVCenter)


                    ## Ajout du logo CEN NA en haut à gauche de la page
                    logo = QgsLayoutItemPicture(self.layout)
                    logo.setResizeMode(QgsLayoutItemPicture.Zoom)
                    logo.setMode(QgsLayoutItemPicture.FormatRaster)
                    logo.attemptMove(self.template_parameters['logo_position'])
                    logo.setFixedSize(self.template_parameters['logo_size'])
                    logo.setPicturePath(resources_path("icons","CEN_RA.png"))
                    self.layout.addLayoutItem(logo)


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

                    legend.setId('legende_model1')
                    # legend.setTitle('Legende')
                    legend.adjustBoxSize()
                    legend.setFrameEnabled(False)
                    legend.setAutoUpdateModel(False)

                    legend.setLinkedMap(self.map_modele_test)
                    self.layout.addItem(legend)

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

                    checked_items = self.mComboBox_2.checkedItems()

                    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)
                        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.adjustBoxSize()
                self.layout.refresh()

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


                ## 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.attemptMove(self.template_parameters['scalebarnumeric_position'])
                self.scalebarnumeric_qpt.attemptResize(self.template_parameters['scalebarnumeric_size'])

                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.applyDefaultSize()
                self.scalebar_qpt.applyDefaultSettings()

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

                self.scalebar_qpt.attemptMove(self.template_parameters['scalebar_position'])
                self.scalebar_qpt.attemptResize(self.template_parameters['scalebar_size'])


                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","NorthArrow_02.svg"))
                self.layout.addLayoutItem(north)
                north.attemptMove(self.template_parameters['north_position'])
                north.attemptResize(self.template_parameters['north_size'])

                # ajout note info:
                info = ["Réalisation : " + "CEN Rhône-Alpes (" + date.today().strftime(
                    "%d/%m/%Y") + ")"]
                info2 = ["Source : " + self.lineEdit_4.text()]
                credit_text = QgsLayoutItemLabel(self.layout)
                credit_text.setText(info[0])
                credit_text.setFont(QFont("Calibri", 9))
                credit_text.setHAlign(Qt.AlignRight)
                credit_text.setVAlign(Qt.AlignVCenter)
                credit_text.setItemRotation(-90)
                credit_text2 = QgsLayoutItemLabel(self.layout)
                credit_text2.setText(info2[0])
                credit_text2.setFont(QFont("Calibri", 9))
                credit_text2.setHAlign(Qt.AlignRight)
                credit_text2.setVAlign(Qt.AlignVCenter)
                credit_text.attemptMove(self.template_parameters['credit_text_position'])
                credit_text.attemptResize(self.template_parameters['credit_text_size'])
                credit_text2.attemptMove(self.template_parameters['credit_text2_position'])
                credit_text2.attemptResize(self.template_parameters['credit_text2_size'])
                self.layout.addLayoutItem(credit_text)
                self.layout.addLayoutItem(credit_text2)

                # 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:
                project.layoutManager().removeLayout(existing_layout)

                result = project.layoutManager().addLayout(self.layout)



        self.manager.addLayout(self.layout)
        fichier_mise_en_page = self.lineEdit_2.text()
        layout_modifie = QgsProject.instance().layoutManager().layoutByName(fichier_mise_en_page)
        iface.openLayoutDesigner(layout_modifie)

    def actualisation_mise_en_page(self):


        if self.radioButton_6.isChecked() and self.radioButton_7.isChecked():

            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A4', QgsLayoutItemPage.Portrait)

            self.template_parameters['map_size'] = QgsLayoutSize(199, 175, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['map_position'] = QgsLayoutPoint(5, 25, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['title_size'] = QgsLayoutSize(200, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['title_position'] = QgsLayoutPoint(5, 2, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['subtitle_size'] = QgsLayoutSize(200, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['subtitle_position'] = QgsLayoutPoint(5, 12, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['logo_size'] = QgsLayoutSize(46, 16, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['logo_position'] = QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['legend_size'] = QgsLayoutSize(405, 203, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['legend_position'] = QgsLayoutPoint(5, 205, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebarnumeric_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebarnumeric_position'] = QgsLayoutPoint(140, 228, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebar_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebar_position'] = QgsLayoutPoint(145, 215, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['north_size'] = QgsLayoutSize(12, 12, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['north_position'] = QgsLayoutPoint(193, 214, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text_position'] = QgsLayoutPoint(205, 125, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text2_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text2_position'] = QgsLayoutPoint(104, 201, QgsUnitTypes.LayoutMillimeters)



        if self.radioButton_6.isChecked() and self.radioButton_8.isChecked():

            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A4', QgsLayoutItemPage.Landscape)

            self.template_parameters['map_size'] = QgsLayoutSize(285, 145, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['map_position'] = QgsLayoutPoint(6, 23, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['title_size'] = QgsLayoutSize(286, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['title_position'] = QgsLayoutPoint(5, 2, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['subtitle_size'] = QgsLayoutSize(286, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['subtitle_position'] = QgsLayoutPoint(5, 10, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['logo_size'] = QgsLayoutSize(46, 16, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['logo_position'] = QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['legend_size'] = QgsLayoutSize(405, 203, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['legend_position'] = QgsLayoutPoint(5, 168, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebarnumeric_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebarnumeric_position'] = QgsLayoutPoint(207, 193, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebar_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebar_position'] = QgsLayoutPoint(207, 180, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['north_size'] = QgsLayoutSize(8.4, 12.5, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['north_position'] = QgsLayoutPoint(273, 182, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text_position'] = QgsLayoutPoint(291.5, 123, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text2_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text2_position'] = QgsLayoutPoint(189, 168.5, QgsUnitTypes.LayoutMillimeters)



        if self.radioButton_5.isChecked() and self.radioButton_7.isChecked():

            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A3', QgsLayoutItemPage.Portrait)


            self.template_parameters['map_size'] = QgsLayoutSize(285, 260, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['map_position'] = QgsLayoutPoint(6, 23, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['title_size'] = QgsLayoutSize(286, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['title_position'] = QgsLayoutPoint(5, 2, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['subtitle_size'] = QgsLayoutSize(286, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['subtitle_position'] = QgsLayoutPoint(5, 10, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['logo_size'] = QgsLayoutSize(46, 16, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['logo_position'] = QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['legend_size'] = QgsLayoutSize(405, 203, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['legend_position'] = QgsLayoutPoint(5, 284, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebarnumeric_size'] = QgsLayoutSize(50, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebarnumeric_position'] = QgsLayoutPoint(207, 310, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebar_size'] = QgsLayoutSize(50, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebar_position'] = QgsLayoutPoint(207, 298, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['north_size'] = QgsLayoutSize(8.4, 12.5, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['north_position'] = QgsLayoutPoint(273, 297, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text_position'] = QgsLayoutPoint(291.5, 123, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text2_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text2_position'] = QgsLayoutPoint(189, 284, QgsUnitTypes.LayoutMillimeters)



        if self.radioButton_5.isChecked() and self.radioButton_8.isChecked():

            pc = self.layout.pageCollection()
            pc.pages()[0].setPageSize('A3', QgsLayoutItemPage.Landscape)

            self.template_parameters['map_size'] = QgsLayoutSize(408.5, 222, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['map_position'] = QgsLayoutPoint(5, 23.5, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['title_size'] = QgsLayoutSize(409, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['title_position'] = QgsLayoutPoint(5, 2, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['subtitle_size'] = QgsLayoutSize(409, 8, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['subtitle_position'] = QgsLayoutPoint(5, 10, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['logo_size'] = QgsLayoutSize(46, 16, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['logo_position'] = QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['legend_size'] = QgsLayoutSize(405, 203, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['legend_position'] = QgsLayoutPoint(5, 249, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebarnumeric_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebarnumeric_position'] = QgsLayoutPoint(323, 282, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['scalebar_size'] = QgsLayoutSize(55, 15, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['scalebar_position'] = QgsLayoutPoint(323, 270, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['north_size'] = QgsLayoutSize(8.4, 12.5, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['north_position'] = QgsLayoutPoint(402, 270, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text_position'] = QgsLayoutPoint(415, 123, QgsUnitTypes.LayoutMillimeters)

            self.template_parameters['credit_text2_size'] = QgsLayoutSize(100, 3.9, QgsUnitTypes.LayoutMillimeters)
            self.template_parameters['credit_text2_position'] = QgsLayoutPoint(313, 247, QgsUnitTypes.LayoutMillimeters)

    def bar_echelle_auto(self, echelle, bar_echelle):
       
        if echelle.scale() >= 45000:
            bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers)
            bar_echelle.setUnitLabel("km")
            bar_echelle.setUnitsPerSegment(1.5)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceKilometers)
            # self.scalebar_test.setUnitLabel("km")
            # self.scalebar_test.setUnitsPerSegment(1.5)

        elif echelle.scale() >= 30000:
            bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers)
            bar_echelle.setUnitLabel("km")
            bar_echelle.setUnitsPerSegment(1)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceKilometers)
            # self.scalebar_test.setUnitLabel("km")
            # self.scalebar_test.setUnitsPerSegment(1)

        elif echelle.scale() >= 20000:
            bar_echelle.setUnits(QgsUnitTypes.DistanceKilometers)
            bar_echelle.setUnitLabel("km")
            bar_echelle.setUnitsPerSegment(0.5)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceKilometers)
            # self.scalebar_test.setUnitLabel("km")
            # self.scalebar_test.setUnitsPerSegment(0.5)

        elif echelle.scale() >= 9000:
            bar_echelle.setUnits(QgsUnitTypes.DistanceMeters)
            bar_echelle.setUnitLabel("m")
            bar_echelle.setUnitsPerSegment(250)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceMeters)
            # self.scalebar_test.setUnitLabel("m")
            # self.scalebar_test.setUnitsPerSegment(250)

        elif echelle.scale() >= 5000:
            bar_echelle.setUnits(QgsUnitTypes.DistanceMeters)
            bar_echelle.setUnitLabel("m")
            bar_echelle.setUnitsPerSegment(100)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceMeters)
            # self.scalebar_test.setUnitLabel("m")
            # self.scalebar_test.setUnitsPerSegment(100)

        else:
            bar_echelle.setUnits(QgsUnitTypes.DistanceMeters)
            bar_echelle.setUnitLabel("m")
            bar_echelle.setUnitsPerSegment(50)
            # self.scalebar_test.setUnits(QgsUnitTypes.DistanceMeters)
            # self.scalebar_test.setUnitLabel("m")
            # self.scalebar_test.setUnitsPerSegment(50)


        bar_echelle.update()
