# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Plugin
                                 A QGIS plugin
 This plugin connects to the NDFF api
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2021-12-20
        copyright            : (C) 2021 by Zuidt
        email                : richard@zuidt.nl
        git sha              : $Format:%H$
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
 This script initializes the plugin, making it known to QGIS.
"""

import logging

from qgis.core import (
    Qgis,
)
from qgis.gui import (
    QgisInterface,
)

# The name of logger we use in this plugin.
# It is created in the plugin.py and logs to the QgsMessageLog under the given LOGGER_NAME tab
LOGGER_NAME = "ndff_connector_plugin"
PLUGIN_DIALOGS_TITLE = "NDFF Connector Plugin"


class QgisLogHandler(logging.StreamHandler):
    """
    Special logger which will make that logging will show up in the QGIS MessageLog panel.

    Some magic to make it possible to use code like:

        import logging
        from . import LOGGER_NAME
        log = logging.getLogger(__name__)

    in all the plugin code, and then it will show up in the QgsMessageLog (too)

    """

    def __init__(self, topic):
        """
        Constructor for this QgisLogHandler
        """
        logging.StreamHandler.__init__(self)
        # topic is used both as logger id and for tab
        self.topic = topic

        """"
          Qgis.MessageLevel:
            Info = 0,     //!< Information message
            Warning = 1,  //!< Warning message
            Critical = 2, //!< Critical/error message
            Success = 3,  //!< Used for reporting a successful operation
            NoLevel = 4,  //!< No level

          Python logging:
            CRITICAL = 50
            ERROR = 40
            WARNING = 30
            INFO = 20
            DEBUG = 10
            NOTSET = 0
        """

        self.level_to_qgis = {
            0: Qgis.MessageLevel.NoLevel,
            10: Qgis.MessageLevel.Info,
            20: Qgis.MessageLevel.Info,
            30: Qgis.MessageLevel.Warning,
            40: Qgis.MessageLevel.Warning,
            50: Qgis.MessageLevel.Critical,
        }

    def emit(self, record):
        """
        Below makes sure that logging of 'self' will show the representation of the object.
        Without this it will not be shown because it is something like
        <qgisnetworklogger.plugin.QgisNetworkLogger object at 0x7f580dac6b38>
        which looks like a html element so is not shown in the html panel
        """
        msg = record.getMessage().replace("<", "&lt;").replace(">", "&gt;")
        from qgis.core import (
            QgsMessageLog,  # we need this... else QgsMessageLog is None after a plugin reload
        )

        QgsMessageLog.logMessage(
            f"{record.filename}:{record.lineno} - {msg}",
            self.topic,
            self.level_to_qgis[record.levelno],
        )


# using the root logger here, so we also can view the api logging if needed
log = logging.getLogger(__name__)

# silencing some noisy modules
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("PyQt5").setLevel(logging.WARNING)
logging.getLogger("shapely").setLevel(logging.WARNING)

# to silence the api/connector messages, these are set to WARNING
# so to SHOW: COMMENT the following lines (then log level will be DEBUG)
# logging.getLogger('ndff_connector_plugin.ext.ndff.api').setLevel(logging.WARNING)
# logging.getLogger('ndff_connector_plugin.ext.ndff.connector').setLevel(logging.WARNING)

# to silence ALL plugin messages, set this one to WARNING
# so to SHOW: COMMENT this lines (then log level will be DEBUG)
logging.getLogger("ndff_connector_plugin").setLevel(logging.WARNING)

# checking below is needed, else we add this handler every time the plugin
# is reloaded (during development), then the msg is emitted several times
if not log.hasHandlers():
    handler = QgisLogHandler(LOGGER_NAME)
    handler.setFormatter(logging.Formatter("%(name)s - %(message)s"))
    log.addHandler(handler)

# set logging level (NOTSET = no, else: DEBUG or INFO)
log.setLevel(logging.INFO)
log.propagate = True


# noinspection PyPep8Naming
# ruff: noqa: N802
def classFactory(iface: QgisInterface):  # pylint: disable=invalid-name
    """Load NdffConnectorPlugin class from file ndffc_plugin.py.

    This is the default starting point of a QGIS plugin, to LOAD a plugin in QGIS.

    :param iface: A QGIS interface instance.
    :type iface: QgsInterface
    """
    #
    from .ndffc_plugin import NdffConnectorPlugin

    return NdffConnectorPlugin(iface)
