# Form implementation generated from reading ui file 'c:\Users\aky547\GitHub\SemesterapparatsManager\src\ui\dialogs\mail_preview.ui'
#
# Created by: PySide6 UI code generator 6.3.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.


from PySide6 import QtCore, QtGui, QtWidgets
import subprocess
import tempfile
import os
import re
from omegaconf import OmegaConf

config = OmegaConf.load("config.yaml")

class Ui_eMailPreview(object):

    def setupUi(
        self,
        eMailPreview,
        app_id="",
        app_name="",
        app_subject="",
        prof_name="",
        data=None,
    ):
        eMailPreview.setObjectName("eMailPreview")
        eMailPreview.resize(676, 676)
        self.buttonBox = QtWidgets.QDialogButtonBox(eMailPreview)
        self.buttonBox.setGeometry(QtCore.QRect(310, 630, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayoutWidget = QtWidgets.QWidget(eMailPreview)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 661, 621))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_5.setObjectName("label_5")
        self.gridLayout.addWidget(self.label_5, 0, 0, 1, 1)
        self.prof_name = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.prof_name.setObjectName("prof_name")
        self.gridLayout.addWidget(self.prof_name, 2, 2, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignLeading|QtCore.Qt.AlignmentFlag.AlignLeft|QtCore.Qt.AlignmentFlag.AlignTop)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 5, 0, 1, 1)
        self.mail_name = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.mail_name.setObjectName("mail_name")
        self.gridLayout.addWidget(self.mail_name, 1, 2, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1)
        self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_4.setObjectName("label_4")
        self.gridLayout.addWidget(self.label_4, 3, 0, 1, 1)
        self.mail_header = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.mail_header.setObjectName("mail_header")
        self.gridLayout.addWidget(self.mail_header, 3, 2, 1, 1)
        self.label = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.comboBox = QtWidgets.QComboBox(self.gridLayoutWidget)
        self.comboBox.setObjectName("comboBox")
        self.gridLayout.addWidget(self.comboBox, 0, 2, 1, 1)
        self.mail_body = QtWidgets.QTextEdit(self.gridLayoutWidget)
        self.mail_body.setObjectName("mail_body")
        self.gridLayout.addWidget(self.mail_body, 5, 2, 1, 1)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.gender_male = QtWidgets.QRadioButton(self.gridLayoutWidget)
        self.gender_male.setObjectName("gender_male")
        self.horizontalLayout_3.addWidget(self.gender_male)
        self.gender_female = QtWidgets.QRadioButton(self.gridLayoutWidget)
        self.gender_female.setObjectName("gender_female")
        self.horizontalLayout_3.addWidget(self.gender_female)
        self.gender_non = QtWidgets.QRadioButton(self.gridLayoutWidget)
        self.gender_non.setObjectName("gender_non")
        self.horizontalLayout_3.addWidget(self.gender_non)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem)
        self.gridLayout.addLayout(self.horizontalLayout_3, 4, 2, 1, 1)
        self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_6.setObjectName("label_6")
        self.gridLayout.addWidget(self.label_6, 4, 0, 1, 1)

        self.retranslateUi(eMailPreview)
        self.buttonBox.accepted.connect(eMailPreview.accept) # type: ignore
        self.buttonBox.rejected.connect(eMailPreview.reject) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(eMailPreview)
        self._appid = app_id
        self._appname = app_name
        self._subject = app_subject
        self.prof_name.setText(prof_name)
        self._mail_data = ""
        self._data = data
        self.load_mail_templates()
        self.comboBox.addItem("")
        self.comboBox.setCurrentText("")
        self.buttonBox.accepted.connect(self.save_mail)
        self.comboBox.currentIndexChanged.connect(self.set_mail)
        self.gender_female.clicked.connect(self.set_mail)
        self.gender_male.clicked.connect(self.set_mail)
        self.gender_non.clicked.connect(self.set_mail)

    def retranslateUi(self, eMailPreview):
        _translate = QtCore.QCoreApplication.translate
        eMailPreview.setWindowTitle(_translate("eMailPreview", "Dialog"))
        self.label_5.setText(_translate("eMailPreview", "Art"))
        self.label_3.setText(_translate("eMailPreview", "Mail"))
        self.label_2.setText(_translate("eMailPreview", "Prof"))
        self.label_4.setText(_translate("eMailPreview", "Betreff"))
        self.label.setText(_translate("eMailPreview", "eMail"))
        self.gender_male.setText(_translate("eMailPreview", "M"))
        self.gender_female.setText(_translate("eMailPreview", "W"))
        self.gender_non.setText(_translate("eMailPreview", "Divers"))
        self.label_6.setText(_translate("eMailPreview", "Geschlecht"))

    def get_greeting(self):
        if self.gender_male.isChecked():
            return "Sehr geehrter Herr"
        elif self.gender_female.isChecked():
            return "Sehr geehrte Frau"
        elif self.gender_non.isChecked():
            return "Guten Tag"
            

    def set_mail(self):
        email_template = self.comboBox.currentText()
        if email_template == "":
            return
        with open(f"mail_vorlagen/{email_template}", "r", encoding="utf-8") as f:
            mail_template = f.read()
        header = re.findall(r"Subject: (.*)", mail_template)
        if header:
            email_header = header[0]
        else:
            email_header = email_template.split(".eml")[0]
        self.mail_header.setText(email_header)
        self.mail_data = mail_template.split("<html>")[0]
        mail_html = mail_template.split("<html>")[1]
        mail_html = "<html>" + mail_html
        mail_html = mail_html.format(
            Profname=self.prof_name.text().split(" ")[1], Appname=self._appname, AppNr=self._appid, AppSubject = self._subject,greeting = self.get_greeting()
        )

        self.mail_body.setHtml(mail_html)
    def load_mail_templates(self):
        mail_templates = os.listdir("mail_vorlagen")
        mail_templates = [f for f in mail_templates if f.endswith(".eml")]
        print(mail_templates)
        self.comboBox.addItems(mail_templates)

    def save_mail(self):
        # create a temporary file
        mail_header = self.mail_header.text()
        mail_body = self.mail_body.toHtml()
        mail = self.mail_data + mail_body
        mail = mail.replace("Subject:", f"Subject: {mail_header}")
        directory = config["database"]["tempdir"]
        directory = directory.replace("~", str(os.path.expanduser("~")))
        with tempfile.NamedTemporaryFile(
            mode="w", delete=False, suffix=".eml", encoding="utf-8", dir=directory
        ) as f:
            f.write(mail)
            self.mail_path = f.name
        print(self.mail_path)
        # open the file using thunderbird
        subprocess.Popen([f"{self.mail_path}"])
        # delete the file
        # os.remove(self.mail_path)

def launch():
    app = QtWidgets.QApplication([])
    eMailPreview = QtWidgets.QDialog()
    ui = Ui_eMailPreview()
    ui.setupUi(eMailPreview, "1","Test","Biologie","Kirchner, Alexander")
    eMailPreview.show()
    app.exec()