# -*- coding: utf-8 -*-
"""
/***************************************************************************
 LayoutPanelDockWidget
                                 A QGIS plugin
 Add a panel to manage layouts without blocking the main interface
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2022-02-09
        git sha              : $Format:%H$
        copyright            : (C) 2022 by Atelier JBP
        email                : jbpeter@outlook.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
import re

from qgis.PyQt import QtGui, QtWidgets, uic, QtXml
from qgis.PyQt.QtCore import pyqtSignal, Qt, QUrl, QDir, QFileInfo, QFileSystemWatcher
from qgis.core import QgsProject, QgsPrintLayout, QgsLayoutExporter, QgsSettings, QgsReadWriteContext, QgsApplication, QgsUnitTypes

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


class LayoutPanelDockWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, iface, parent=None):
        """Initialize the layout panel"""
        super(LayoutPanelDockWidget, self).__init__(parent)
        self.setupUi(self)

        self.iface = iface

        # Used to store the initial name of the layout before entering editor mode
        self.name_before_rename = None

        self.pbCreateLayout.clicked.connect(self.createNewLayout)
        self.pbDeleteLayout.clicked.connect(self.removeSelectedLayouts)
        self.listWidget.itemDoubleClicked.connect(self.openCurrentLayout)
        self.listWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.listWidget.customContextMenuRequested.connect(self.openContextMenu)
        self.listWidget.itemDelegate().closeEditor.connect(self.renameLayoutClosedEditor)
        self.mLineEdit.valueChanged.connect(self.updateLayoutWidgetList)

        QgsProject.instance().readProject.connect(self.updateProjectInstance)
        QgsProject.instance().cleared.connect(self.updateProjectInstance)
        QgsProject.instance().layoutManager().layoutAdded.connect(self.updateLayoutWidgetList)
        QgsProject.instance().layoutManager().layoutRemoved.connect(self.updateLayoutWidgetList)
        QgsProject.instance().layoutManager().layoutRenamed.connect(self.updateLayoutWidgetList)

        # Watch layout template folder for changes
        self.template_dir = QDir(QgsApplication.qgisSettingsDirPath() + '/composer_templates')
        self.watchFolder = QFileSystemWatcher([self.template_dir.absolutePath()])
        self.watchFolder.directoryChanged.connect(self.updateTemplateMenu)
        self.watchFolder.fileChanged.connect(self.updateTemplateMenu)

        # Initialise project, layout list and template menu
        self.updateProjectInstance()
        self.updateLayoutWidgetList()
        self.updateTemplateMenu()

    def closeEvent(self, event):
        """Close the plugin"""
        self.closingPlugin.emit()
        event.accept()

    def updateProjectInstance(self):
        """Update project instance and project layout manager"""
        self.template_dir = QDir(QgsApplication.qgisSettingsDirPath() + '/composer_templates')
        self.mLineEdit.clearValue()
        self.project_instance = QgsProject.instance()
        self.project_layout_manager = self.project_instance.layoutManager()
        self.updateLayoutWidgetList()

    def updateLayoutWidgetList(self):
        """Generate the list of layouts"""
        layout_list = self.project_layout_manager.layouts()
        self.listWidget.clear()
        search_value = self.mLineEdit.value().replace("*", r"\*").replace("+", r"\+").replace("(", r"\(")\
            .replace(")",r"\)").replace("?", r"\?").replace("[", r"\[").replace("]", r"\]")
        for layout in layout_list:
            # necessary to ensure that tooltips are updated when layout format or page count changes
            layout.pageCollection().changed.connect(self.updateLayoutWidgetList)
            match = bool(re.search(search_value, layout.name(), re.IGNORECASE))
            if match:
                layout = self.project_layout_manager.layoutByName(layout.name())
                layout_page_collection = layout.pageCollection()
                page_count = layout_page_collection.pageCount()
                if layout_page_collection.hasUniformPageSizes():
                    page_size = layout_page_collection.maximumPageSize()
                    units = QgsUnitTypes.encodeUnit(layout.units())
                    page_size_text = f'{page_size.width()}x{page_size.height()} {units}'
                else:
                    page_size_text = 'variable'

                item = QtWidgets.QListWidgetItem()
                item.setText(layout.name())
                item.setIcon(QtGui.QIcon(':/plugins/layout_panel/icons/mIconLayout.svg'))
                item.setFlags(item.flags() | Qt.ItemIsEditable)
                item.setToolTip(f'Page Count: {page_count} <br> Page Size: {page_size_text}')
                self.listWidget.addItem(item)

    def updateTemplateMenu(self):
        """Generate the template menu"""
        projectTemplateDir = QDir(QgsApplication.qgisSettingsDirPath())
        projectTemplateDir.cd('composer_templates')
        projectTemplateDir.setFilter(QDir.Files)
        projectTemplateDir.setNameFilters(["*.qpt", "*.QPT"])
        projectTemplateDir.setSorting(QDir.Time)
        layoutTemplateList = []
        for template in projectTemplateDir.entryList():
            layoutTemplateList.append(projectTemplateDir.filePath(template))

        menu = QtWidgets.QMenu()
        if not layoutTemplateList:
            layoutTemplateAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionNewLayout.svg"), 'Template folder is empty')
            layoutTemplateAction.setEnabled(False)
        actions = []
        for layoutTemplatePath in layoutTemplateList:
            layoutTemplateAction = QtWidgets.QAction(QFileInfo(layoutTemplatePath).baseName(), self)
            layoutTemplateAction.setIcon(QtGui.QIcon(":/plugins/layout_panel/icons/mActionNewLayoutFromTemplate.svg"))
            layoutTemplateAction.setData(["layoutTemplateAction",layoutTemplatePath])
            actions.append(layoutTemplateAction)
        menu.addActions(actions)
        menu.addSeparator()
        selectTemplateAction = menu.addAction("Choose Another Template File...")
        selectTemplateAction.setData(["selectTemplateAction", projectTemplateDir.absolutePath()])
        openTemplateFolderAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mIconFolder.svg"), "Open Template Folder")
        openTemplateFolderAction.setData(["openTemplateFolderAction", projectTemplateDir.absolutePath()])
        self.tbTemplateMenu.setMenu(menu)
        menu.triggered.connect(self.templateMenuTriggered)

    def templateMenuTriggered(self, layoutTemplateAction):
        """Called when template menu is triggered"""
        if layoutTemplateAction.data()[0] == "openTemplateFolderAction":
            QtGui.QDesktopServices.openUrl(QUrl.fromLocalFile(layoutTemplateAction.data()[1]))
        elif layoutTemplateAction.data()[0] == "selectTemplateAction":
            fname = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose a template to create a new layout', layoutTemplateAction.data()[1], 'Layout templates (*.qpt *.QPT)')
            if fname[0] != '':
                self.createLayoutFromTemplate(fname[0])
        elif layoutTemplateAction.data()[0] == "layoutTemplateAction":
            self.createLayoutFromTemplate(layoutTemplateAction.data()[1])

    def openContextMenu(self, position):
        """Create the contextual menu for the layout widgetlist"""
        selectedLayouts = self.listWidget.selectedItems()
        if len(selectedLayouts) == 0: # Context menu if no layout is selected
            menu = QtWidgets.QMenu()
            newLayoutAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionNewLayout.svg"), "New Print Layout")
            menu.addSeparator()
            exportMenu = menu.addMenu("Export All Layouts as...")
            exportPDFAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsPDF.svg"), "Export as PDF")
            exportImageAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveMapAsImage.svg"), "Export as Image")
            exportSvgAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsSVG.svg"), "Export as SVG")
            action = menu.exec_(self.listWidget.mapToGlobal(position))
            if action == newLayoutAction:
                self.createNewLayout()
            elif action == exportPDFAction:
                self.exportLayoutPDF()
            elif action == exportImageAction:
                self.exportLayoutImage()
            elif action == exportSvgAction:
                self.exportLayoutSvg()

        elif len(selectedLayouts) == 1: # Context menu if only one layout is selected
            menu = QtWidgets.QMenu()
            openAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mIconLayout.svg"), "Open Layout")
            duplicateAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionNewLayout.svg"), "Duplicate Layout")
            renameAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionRename.svg"),"Rename Layout")
            removeAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionDeleteSelected.svg"),"Remove Layout...")
            menu.addSeparator()
            saveAsTemplateAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveLayoutTemplate.svg"), "Save Layout as Template...")
            menu.addSeparator()
            exportMenu=menu.addMenu("Export Layout as...")
            exportPDFAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsPDF.svg"), "Export as PDF")
            exportImageAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveMapAsImage.svg"), "Export as Image")
            exportSvgAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsSVG.svg"), "Export as SVG")
            action = menu.exec_(self.listWidget.mapToGlobal(position))
            if action == removeAction:
                self.removeSelectedLayouts()
            elif action == openAction:
                self.openCurrentLayout()
            elif action == duplicateAction:
                self.duplicateLayout()
            elif action == renameAction:
                self.renameLayout()
            elif action == saveAsTemplateAction:
                self.saveAsTemplate()
            elif action == exportPDFAction:
                self.exportLayoutPDF()
            elif action == exportImageAction:
                self.exportLayoutImage()
            elif action == exportSvgAction:
                self.exportLayoutSvg()
            else:
                print("Code not found")

        else: # Context menu if multiple layouts are selected
            menu = QtWidgets.QMenu()
            duplicateAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionNewLayout.svg"),"Duplicate Layouts")
            removeAction = menu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionDeleteSelected.svg"), "Remove Layouts...")
            menu.addSeparator()
            exportMenu = menu.addMenu("Export Layouts as...")
            exportPDFAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsPDF.svg"), "Export as PDF")
            exportImageAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveMapAsImage.svg"), "Export as Image")
            exportSvgAction = exportMenu.addAction(QtGui.QIcon(":/plugins/layout_panel/icons/mActionSaveAsSVG.svg"),"Export as SVG")
            action = menu.exec_(self.listWidget.mapToGlobal(position))
            if action == removeAction:
                self.removeSelectedLayouts()
            elif action == duplicateAction:
                self.duplicateLayout()
            elif action == exportPDFAction:
                self.exportLayoutPDF()
            elif action == exportImageAction:
                self.exportLayoutImage()
            elif action == exportSvgAction:
                self.exportLayoutSvg()
            else:
                return

    def openCurrentLayout(self):
        """Open currently selected layout in editor"""
        layout = self.project_layout_manager.layoutByName(self.listWidget.selectedItems()[0].text())
        self.iface.openLayoutDesigner(layout)

    def createNewLayout(self):
        """Create a new blank layout"""
        iterator = 1
        while True:
            if self.project_layout_manager.layoutByName('Layout ' + str(iterator)) is None:
                layout_name = "Layout " + str(iterator)
                layout = QgsPrintLayout(self.project_instance)
                layout.initializeDefaults()
                layout.setName(layout_name)
                self.project_layout_manager.addLayout(layout)
                return
            iterator = iterator + 1

    def createLayoutFromTemplate(self, layout_template_path):
        """Create a new layout based on a template file"""
        document = QtXml.QDomDocument()
        with open(layout_template_path) as file:
            content = file.read()
        document.setContent(content)
        template_name = QFileInfo(layout_template_path).baseName()
        iterator = 1
        while True:
            if self.project_layout_manager.layoutByName(template_name + ' ' + str(iterator)) is None :
                layout = QgsPrintLayout(self.project_instance)
                layout_name = template_name + ' ' + str(iterator)
                layout.loadFromTemplate(document, QgsReadWriteContext())
                layout.setName(layout_name)
                self.project_layout_manager.addLayout(layout)
                return
            iterator = iterator + 1

    def duplicateLayout(self):
        """Duplicate one or multiple selected layouts"""
        selected_items = self.listWidget.selectedItems()
        list_layout_names = []
        for layoutItem in selected_items:
            list_layout_names.append(layoutItem.text())
        for layoutName in list_layout_names:
            iterator = 1
            while True:
                duplicate_layout_name = layoutName + ' copy ' + str(iterator)
                if self.project_layout_manager.layoutByName(duplicate_layout_name) is None:
                    layout = self.project_layout_manager.layoutByName(layoutName)
                    self.project_layout_manager.duplicateLayout(layout, duplicate_layout_name)
                    return
                iterator = iterator + 1

    def renameLayout(self):
        """Open editor mode to rename currently selected layout"""
        self.name_before_rename = self.listWidget.selectedItems()[0].text()
        self.listWidget.editItem(self.listWidget.selectedItems()[0])

    def renameLayoutClosedEditor(self, QListWidgetItem):
        """Called when editor mode is closed to rename the layout"""
        if self.project_layout_manager.layoutByName(QListWidgetItem.text()) is None and QListWidgetItem.text() != "":
            if self.name_before_rename != QListWidgetItem.text():
                layout = self.project_layout_manager.layoutByName(self.name_before_rename)
                layout.setName(QListWidgetItem.text())
        else:
            if self.name_before_rename != QListWidgetItem.text():
                self.iface.messageBar().pushWarning('Failed to rename layout', ' Entered layout name already exists or is invalid.')
        self.updateLayoutWidgetList()

    def removeSelectedLayouts(self):
        """Remove one or multiple selected layouts"""
        selected_items = self.listWidget.selectedItems()
        qm = QtWidgets.QMessageBox
        if len(selected_items) == 0:
            return
        elif len(selected_items) == 1:
            ret = qm.question(self, 'Remove Selected Layout',
                              f'Are you sure you want to remove permanently "{selected_items[0].text()}" ?', qm.Yes | qm.No)
        else:
            ret = qm.question(self, 'Remove Selected Layouts',
                              f'Are you sure you want to remove permanently {len(selected_items)} layouts?', qm.Yes | qm.No)
        if ret == qm.Yes:
            layout_names = []
            for item in selected_items:
                layout_names.append(item.text())
            for layout_name in layout_names:
                self.project_layout_manager.removeLayout(self.project_layout_manager.layoutByName(layout_name))

    def saveAsTemplate(self):
        """Save selected layout as template"""
        selected_items = self.listWidget.selectedItems()
        current_layout = self.project_layout_manager.layoutByName(selected_items[0].text())
        file_path = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a file name to save the layout as template',
                                                      self.template_dir.filePath(current_layout.name() + '.qpt'),
                                                      'Layout templates (*.qpt *.QPT)')[0]
        if file_path != '':
            template=current_layout.saveAsTemplate(file_path, QgsReadWriteContext())
            if template:
                href = f'<a href="{QUrl.fromLocalFile(file_path).toString()}">{QDir.toNativeSeparators(file_path)}</a>'
                self.iface.messageBar().pushSuccess('Save as Template', ' Successfully saved layout template to ' + href)

    def exportLayoutPDF(self):
        """Export one or multiple layouts to PDF"""
        default_extension = '.pdf'
        extension_filter = 'PDF files (*.pdf *.PDF)'
        default_filter = 'PDF files (*.pdf *.PDF)'

        lastLayoutExportDir = QgsSettings().value('APP/lastLayoutExportDir')
        if lastLayoutExportDir == "":
            lastUsedFolder = QDir(self.project_instance.homePath())
        else:
            lastUsedFolder = QFileInfo(lastLayoutExportDir).dir()

        layoutList = []
        selectedLayouts = self.listWidget.selectedItems()
        if len(selectedLayouts) == 0: # If nothing is selected, ask for destination folder and export all layouts
            for x in range(self.listWidget.count()):
                layoutList.append(self.project_layout_manager.layoutByName(self.listWidget.item(x).text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)
        elif len(selectedLayouts) == 1:  # If nonly one layout is selected, ask file name and export layout
            layout = (self.project_layout_manager.layoutByName(selectedLayouts[0].text()))
            layoutList.append(layout)
            fname = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a file name to save the layout as PDF',
                                                          lastUsedFolder.filePath(layout.name() + default_extension), extension_filter,default_filter)
            if fname[0] == '': fname = None
        else: # Multiple selection, ask for destination folder and export selected layouts
            for layout in selectedLayouts:
                layoutList.append(self.project_layout_manager.layoutByName(layout.text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)

        if fname:
            QgsSettings().setValue('APP/lastLayoutExportDir', fname[0])
            for layout in layoutList:
                export = QgsLayoutExporter(layout)
                if len(selectedLayouts) == 1: fileName = fname[0]
                else: fileName = QDir(fname).filePath(layout.name() + default_extension)
                export.exportToPdf(fileName, QgsLayoutExporter.PdfExportSettings())
                href = f'<a href="{QUrl.fromLocalFile(fileName).toString()}">{QDir.toNativeSeparators(fileName)}</a>'
                self.iface.messageBar().pushSuccess('Export layout',' Successfully exported layout to ' + href)

    def exportLayoutImage(self):
        """Export one or multiple layouts to image"""
        default_extension = '.png'
        extension_filter = 'PNG format (*.png *.PNG);;BMP format (*.bmp *.BMP);;CUR format (*.cur *.CUR);;ICNS format (*.icns *.ICNS);;ICO format (*.ico *.ICO)' \
                           'JPEG format (*.jpeg *.JPEG);;JPG format (*.jpg *.JPG);;PBM format (*.pbm *.PBM);;PGM format (*.pgm *.PGM);;PPM format (*.ppm *.PPM)' \
                           'TIF format (*.tif *.TIF);;TIFF format (*.tiff *.TIFF);;WBMP format (*.wbmp *.WBMP);;WEBP format (*.webp *.WEBP);;WBM format (*.wbm *.XBM);;XPM format (*.xpm *.XPM)'
        default_filter = 'PNG format (*.png *.PNG)'

        lastLayoutExportDir = QgsSettings().value('APP/lastLayoutExportDir')
        if lastLayoutExportDir == "":
            lastUsedFolder = QDir(self.project_instance.homePath())
        else:
            lastUsedFolder = QFileInfo(lastLayoutExportDir).dir()

        layoutList = []
        selectedLayouts = self.listWidget.selectedItems()
        if len(selectedLayouts) == 0: # If nothing is selected, ask for destination folder and export all layouts
            for x in range(self.listWidget.count()):
                layoutList.append(self.project_layout_manager.layoutByName(self.listWidget.item(x).text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)
        elif len(selectedLayouts) == 1:  # If nonly one layout is selected, ask file name and export layout
            layout = (self.project_layout_manager.layoutByName(selectedLayouts[0].text()))
            layoutList.append(layout)
            fname = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a file name to save the layout as image',
                                                          lastUsedFolder.filePath(layout.name() + default_extension), extension_filter,default_filter)
            if fname[0] == '': fname = None
        else: # Multiple selection, ask for destination folder and export selected layouts
            for layout in selectedLayouts:
                layoutList.append(self.project_layout_manager.layoutByName(layout.text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)

        if fname:
            QgsSettings().setValue('APP/lastLayoutExportDir', fname[0])
            for layout in layoutList:
                export = QgsLayoutExporter(layout)
                if len(selectedLayouts) == 1: fileName = fname[0]
                else: fileName = QDir(fname).filePath(layout.name() + default_extension)
                export.exportToImage(fileName, QgsLayoutExporter.ImageExportSettings())
                href = f'<a href="{QUrl.fromLocalFile(fileName).toString()}">{QDir.toNativeSeparators(fileName)}</a>'
                self.iface.messageBar().pushSuccess('Export layout', ' Successfully exported layout to ' + href)

    def exportLayoutSvg(self):
        """Export one or multiple layouts to SVG"""
        default_extension = '.svg'
        extension_filter = 'SVG format (*.svg *.SVG)'
        default_filter = 'SVG format (*.svg *.SVG)'

        lastLayoutExportDir=QgsSettings().value('APP/lastLayoutExportDir')
        if lastLayoutExportDir=="":
            lastUsedFolder = QDir(self.project_instance.homePath())
        else:
            lastUsedFolder = QFileInfo(lastLayoutExportDir).dir()

        layoutList = []
        selectedLayouts = self.listWidget.selectedItems()
        if len(selectedLayouts) == 0: # If nothing is selected, ask for destination folder and export all layouts
            for x in range(self.listWidget.count()):
                layoutList.append(self.project_layout_manager.layoutByName(self.listWidget.item(x).text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)
        elif len(selectedLayouts) == 1:  # If only one layout is selected, ask file name and export layout
            layout = (self.project_layout_manager.layoutByName(selectedLayouts[0].text()))
            layoutList.append(layout)
            fname = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a file name to save the layout as SVG',
                                                          lastUsedFolder.filePath(layout.name() + default_extension), extension_filter, default_filter)
            if fname[0] == '': fname = None
        else: # Multiple selection, ask for destination folder and export selected layouts
            for layout in selectedLayouts:
                layoutList.append(self.project_layout_manager.layoutByName(layout.text()))
            fname = QtWidgets.QFileDialog.getExistingDirectory(self, 'Choose folder to save multiple files',
                                                               lastUsedFolder.path(),QtWidgets.QFileDialog.ShowDirsOnly)

        if fname:
            QgsSettings().setValue('APP/lastLayoutExportDir', fname[0])
            for layout in layoutList:
                export = QgsLayoutExporter(layout)
                if len(selectedLayouts) == 1: fileName = fname[0]
                else: fileName = QDir(fname).filePath(layout.name() + default_extension)
                export.exportToSvg(fileName, QgsLayoutExporter.SvgExportSettings())
                href = f'<a href="{QUrl.fromLocalFile(fileName).toString()}">{QDir.toNativeSeparators(fileName)}</a>'
                self.iface.messageBar().pushSuccess('Export layout',' Successfully exported layout to ' + href)


#TODO: cleanup the code
#TODO: Export as background task
#TODO: update statusbar
#TODO: translation TR
#TODO: Separate code logic from gui?
#TODO: Filter tool button? filter by size, page count, expression, etc.
#TODO: Add support for reports
#TODO: Support for drag & drop
#TODO: quick print layout?
#TODO: icons for layout templates