# -*- coding: utf-8 -*-
import os

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QStyle, QMessageBox, QWidget
from PyQt5.QtWidgets import QApplication
from qgis.PyQt import uic
from ..i18n import tr

import logging

from ..constants import QGIS_PLUGIN_NAME
from ..logger.qgis_logger_handler import QgisLoggerHandler

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

ICON_NAMES = {
    "info": "SP_MessageBoxInformation",
    "warning": "SP_MessageBoxWarning",
    "critical": "SP_MessageBoxCritical",
}


class MessagesDialog(QtWidgets.QDialog, FORM_CLASS):


    """
        Manages the creation of messages to the adding of messages to the message dialog.
        :ivar logger: logger of the application. Used to keep logs.
        :vartype logger: logging.Logger

    """

    def __init__(self, parent: QWidget=None):
        """
        Constructor.
        :param parent: parent of the message dialog.
        """
        super(MessagesDialog, self).__init__(parent)
        self.setupUi(self)
        self.accept_button.clicked.connect(self.accept)
        self.btn_copy.clicked.connect(self.__copy_msg)
        self.setModal(True)
        self.lstw_messages.setAutoScroll(True)
        self.logger = QgisLoggerHandler(
            QGIS_PLUGIN_NAME,
            level=logging.INFO
        ).get_logger()

    def __copy_msg(self):
        """
            Copy the messages from the dialog to the system clipboard.
        """
        msgs = []
        for i in range(self.lstw_messages.count()):
            msgs.append(self.lstw_messages.item(i).text())
        text = "\n".join(msgs)
        QApplication.clipboard().setText(text)
        if not "TEST_RUNNING" in os.environ:
            QMessageBox.question(None, "Info", tr("Messages copied to clipboard"), QMessageBox.Ok)

    def notify_msg(self, msg_type: str, msg: str):
        """
            Add a new message in the dialog with the symbol from msg_type and the text msg.
            :param msg_type: tag to identify the symbol that will be used.
            :param msg: string with the message that will be added
        """
        # add new message to list
        item = QtWidgets.QListWidgetItem(self.lstw_messages)
        msg_type = msg_type.lower()
        if msg_type not in ICON_NAMES:
            raise BaseException("Invalid message type: {message}".format(message=msg_type))
        pixmapi = getattr(QStyle, ICON_NAMES[msg_type])
        item.setIcon(self.style().standardIcon(pixmapi))
        item.setSizeHint(QtCore.QSize(0, 30))
        item.setText(msg)
        self.lstw_messages.addItem(item)
        try:
            QApplication.processEvents()
            if self.lstw_messages:
                self.lstw_messages.scrollTo(self.lstw_messages.indexFromItem(item))
        except Exception:
            self.logger.error("An error occurred while trying to scroll the window to the new message")

    def clear_messages(self):
        """
            Clean all the messages in the dialog.
        """
        self.lstw_messages.clear()