import os

from PyQt6 import QtGui, QtWidgets, QtCore

from src import Icon

from .dialog_sources import NewMailTemplateDesignerDialog
from src import logger

class MailTemplateDialog(QtWidgets.QDialog, NewMailTemplateDesignerDialog):
    updateSignal = QtCore.pyqtSignal()
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(Icon("edit_note").icon)
        self.setWindowTitle("Mailvorlage erstellen")
        self.placeholder_list.addItem("")
        self.placeholder_list.setCurrentText("")
        self.insertPlaceholder.clicked.connect(self.insert_placeholder)
        self.placeholder_list.currentTextChanged.connect(self.updateDescription)
        self.bold.clicked.connect(self.setFontBold)
        self.italic.clicked.connect(self.setTextFontItalic)
        self.underlined.clicked.connect(self.setTextFontUnderline)
        self.testTemplate.clicked.connect(self.test_template)
        self.fontBox.currentFontChanged.connect(self.setCurrentFont)
        self.fontSize.currentTextChanged.connect(self.setFontSize)
        # buttonbox
        # save button
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Save
        ).clicked.connect(self.save_template)
        # discard button
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Discard
        ).clicked.connect(self.discard_changes)
        # cancel button
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Cancel
        ).clicked.connect(self.closeNow)
        logger.info("Mail template dialog setup complete")
    def save_template(self):
        # print("save triggered")
        # create a dialog to ask for the name of the template
        dialog = QtWidgets.QInputDialog()
        dialog.setInputMode(QtWidgets.QInputDialog.InputMode.TextInput)
        dialog.setLabelText("Bitte geben Sie den Namen des Templates ein:")
        dialog.setWindowTitle("Template speichern")
        dialog.setOkButtonText("Speichern")
        dialog.setCancelButtonText("Abbrechen")
        dialog.setWindowIcon(Icon("save").icon)
        save = dialog.exec()
        template_name = dialog.textValue()
        logger.info("Saving template")
        if template_name != "" and save == 1:
            template = template_name + ".eml"
            if template in os.listdir("mail_vorlagen"):
                logger.error("Template already exists")
                # warning dialog
                dialog = QtWidgets.QMessageBox()
                dialog.setIcon(QtWidgets.QMessageBox.Icon.Warning)
                Icon("warning", dialog)
                dialog.setText(
                    "Ein Template mit diesem Namen existiert bereits. Möchten Sie es überschreiben?"
                )
                dialog.setWindowTitle("Template überschreiben")
                dialog.setStandardButtons(
                    QtWidgets.QMessageBox.StandardButton.Yes
                    | QtWidgets.QMessageBox.StandardButton.No
                )
                dialog.setDefaultButton(QtWidgets.QMessageBox.StandardButton.No)
                ret = dialog.exec()
                if ret == QtWidgets.QMessageBox.StandardButton.No:
                    return
            mail = f"""Subject: {self.subject.text()}
MIME-Version: 1.0
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: 8bit
{self.templateEdit.toHtml()}"""
            html_head = """<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
                """
            mail_base = mail.split("<html>")[0]
            mail_body = mail.split("</head>")[1]
            mail = mail_base + html_head + mail_body
            mail = (
                mail.replace("&lt;", "<")
                .replace("&gt;", ">")
                .replace("&quot;", '"')
                .replace("&amp;", "&")
            )
            with open(f"mail_vorlagen/{template}", "w", encoding="utf-8") as f:
                f.write(mail)
            self.updateSignal.emit()
            self.close()
            logger.success(f"Template {template} saved successfully")
        else:
            # warning dialog
            dialog = QtWidgets.QMessageBox()
            dialog.setIcon(QtWidgets.QMessageBox.Icon.Warning)
            dialog.setWindowIcon(Icon("warning").icon)

            dialog.setText("Bitte geben Sie einen Namen für das Template ein.")
            dialog.setWindowTitle("Fehler beim Speichern")
            dialog.exec()
            return

    def discard_changes(self):
        self.subject.clear()
        self.templateEdit.clear()

    def closeNow(self):
        if self.subject.text() == "" and self.templateEdit.toPlainText() == "":
            self.close()
        else:
            dialog = QtWidgets.QMessageBox()
            dialog.setWindowIcon(Icon("warning").icon)
            dialog.setIcon(QtWidgets.QMessageBox.Icon.Warning)
            dialog.setText("Möchten Sie die Änderungen wirklich verwerfen?")
            dialog.setWindowTitle("Änderungen verwerfen")
            dialog.setStandardButtons(
                QtWidgets.QMessageBox.StandardButton.Yes
                | QtWidgets.QMessageBox.StandardButton.No
            )
            dialog.setDefaultButton(QtWidgets.QMessageBox.StandardButton.No)
            ret = dialog.exec()
            if ret == QtWidgets.QMessageBox.StandardButton.Yes:
                self.close()

    def updateDescription(self):
        # print("update triggered")
        # print(self.placeholder_list.currentText())
        placeholders = {
            "anrede": "Die Anrede beinhaltet sowohl Person als auch Sehr geehrte/r; dargestellt als: {greeting}",
            "apparatsfach": "Das Fach, in welchem der Apparat angelegt wurde; dargestellt als: {AppSubject}",
            "apparatsname": "Der Name des Apparats; dargestellt als: {Appname}",
            "apparatsnummer": "Die Nummer des Apparats; dargestellt als: {AppNr}",
            "dozentname": "Der Name des Dozenten / der Dozentin; dargestellt als: {Profname}",
            "signatur": "Die persönliche / allgemeine Signatur am ende der Mail; dargestellt als: {signature}",
            "": " ",
        }
        for (
            key,
            item,
        ) in placeholders.items():
            if key in self.placeholder_list.currentText().lower():
                self.lineEdit.setText(item)
                break

    def setCurrentFont(self):
        font = self.fontBox.currentFont()
        font.setPointSize(int(self.fontSize.currentText()))
        self.templateEdit.setFont(font)

    def setFontSize(self):
        size = self.fontSize.currentText()
        self.templateEdit.setFontPointSize(int(size))

    def setFontBold(self):
        if self.bold.isChecked():
            self.templateEdit.setFontWeight(QtGui.QFont.Weight.Bold)
        else:
            self.templateEdit.setFontWeight(QtGui.QFont.Weight.Normal)

    def setTextFontItalic(self):
        if self.italic.isChecked():
            self.templateEdit.setFontItalic(True)
        else:
            self.templateEdit.setFontItalic(False)

    def setTextFontUnderline(self):
        if self.underlined.isChecked():
            self.templateEdit.setFontUnderline(True)
        else:
            self.templateEdit.setFontUnderline(False)

    def test_template(self):
        placeholders = [
            "{greeting}",
            "{AppSubject}",
            "{Appname}",
            "{AppNr}",
            "{Profname}",
            "{signature}",
        ]
        mail_subject = self.subject.text()
        mail_body = self.templateEdit.toHtml()
        missing_body = []
        missing_subject = []
        try:
            assert placeholders[2] in mail_subject
        except AssertionError:
            missing_subject.append(placeholders[2])
        # check if all placeholders are in the mail body
        for placeholder in placeholders:
            try:
                assert placeholder in mail_body
            except AssertionError:
                missing_body.append(placeholder)
        if missing_body != []:
            # warning dialog
            Icon("template_fail", self.testTemplate)
            dialog = QtWidgets.QMessageBox()
            dialog.setWindowIcon(Icon("warning").icon)

            dialog.setText("Folgende Platzhalter fehlen im Template:")

            missing = (
                "Betreff:\n"
                + "\n".join(missing_subject)
                + "\n\n"
                + "Mailtext:\n"
                + "\n".join(missing_body)
            )

            dialog.setInformativeText(f"{missing}")
            dialog.setWindowTitle("Fehlende Platzhalter")
            dialog.exec()
            self.testTemplate.setText("Template testen")
        else:
            self.testTemplate.setText("✔")

    def insert_placeholder(self):
        placeholder = {
            "anrede": "{greeting}",
            "apparatsfach": "{AppSubject}",
            "apparatsname": "{Appname}",
            "apparatsnummer": "{AppNr}",
            "dozentname": "{Profname}",
            "signatur": """<pre class="moz-signature" cols="72">-- 
{signature}
</pre>""",
        }
        cursor = self.templateEdit.textCursor()
        for (
            key,
            item,
        ) in placeholder.items():
            if key in self.placeholder_list.currentText().lower():
                cursor.insertText(item)
                break
        self.templateEdit.setTextCursor(cursor)
        self.templateEdit.setFocus()


def launch_gui():
    app = QtWidgets.QApplication([])
    window = MailTemplateDialog()
    window.show()
    app.exec()


if __name__ == "__main__":
    launch_gui()
