import os
# from qgis.gui import *

from qgis.core import QgsSettings
from qgis.PyQt.QtWidgets import QDialog
from qgis.utils import iface


from .tools.resources import (
    load_ui,
    send_issues,
)
plugin_dir = os.path.dirname(__file__)
end_find = plugin_dir.rfind('\\') + 1

NAME = plugin_dir[end_find:]

EDITOR_CLASS = load_ui('CenRa_IssuesSend.ui')


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

        # place connect here
        self.annuler_button.clicked.connect(self.close)
        self.ok_button.clicked.connect(self.run_sendissues)

    def run_sendissues(self):
        text_titre = self.titre_line.text()
        text_message = self.messages_plain.toPlainText()
        statu_bug = self.check_bug.isChecked()
        statu_aide = self.check_aide.isChecked()
        statu_question = self.check_question.isChecked()
        statu_amelioration = self.check_amelioration.isChecked()
        statu_autre = self.check_autre.isChecked()

        statu = []
        if statu_bug is True:
            statu = statu + [1]
        if statu_aide is True:
            statu = statu + [3]
        if statu_question is True:
            statu = statu + [5]
        if statu_amelioration is True:
            statu = statu + [2]
        if statu_autre is True:
            statu = statu + [6]

        if len(statu) >= 1:
            import qgis
            url = qgis.utils.pluginMetadata(NAME, 'tracker')
            print(text_message)
            send_info = send_issues(url, text_titre, text_message, statu)
            code = send_info.status_code
            print(code)
        else:
            code = 423
        if code == 201:
            iface.messageBar().pushMessage("Envoyer :", "Votre messages à bien été envoyer.", level=0, duration=20)
            self.close()
        elif code == 422:
            iface.messageBar().pushMessage("Erreur :", "Erreur dans le contenu du messages.", level=2, duration=20)
        elif code == 423:
            iface.messageBar().pushMessage("Erreur :", "Pas de sujet sélectionné.", level=2, duration=20)
        elif code == 404:
            iface.messageBar().pushMessage("Missing :", "Le serveur de messagerie est injoignable.", level=1, duration=20)
