import os

# from icecream import ic
from omegaconf import OmegaConf
from PyQt6 import QtWidgets
from PyQt6.QtCore import QThread
from PyQt6.QtCore import pyqtSignal as Signal

from src.backend.database import Database
from src.logic.log import MyLogger
from src.logic.webrequest import BibTextTransformer, WebRequest

# from src.transformers import RDS_AVAIL_DATA
from src.ui.dialogs.Ui_mail_preview import Ui_eMailPreview

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


class BackgroundChecker(QThread):
    """Check all apparats for available Books"""

    pass


class MockAvailCheck:
    def __init__(
        self, links: list = None, appnumber: int = None, parent=None, books=list[dict]
    ):
        if links is None:
            links = []
        super().__init__(parent)
        self.logger = MyLogger("MockAvailChecker")
        self.logger.log_info("Starting worker thread")
        self.logger.log_info(
            "Checking availability for "
            + str(links)
            + " with appnumber "
            + str(appnumber)
            + "..."
        )
        self.links = links
        self.appnumber = appnumber
        self.books = books

    def run(self):
        self.db = Database()
        state = 0
        count = 0
        result = []
        for link in self.links:
            self.logger.log_info("Processing entry: " + str(link))
            data = WebRequest().get_ppn(link).get_data()
            transformer = BibTextTransformer("RDS")
            rds = transformer.get_data(data).return_data("rds_availability")

            for item in rds.items:
                sign = item.superlocation
                loc = item.location
                # ic(item.location, item.superlocation)
                if self.appnumber in sign or self.appnumber in loc:
                    state = 1
                book_id = None
                for book in self.books:
                    if book["bookdata"].signature == link:
                        book_id = book["id"]
                        break
                self.logger.log_info(f"State of {link}: " + str(state))
                print(
                    "lock acquired, updating availability of "
                    + str(book_id)
                    + " to "
                    + str(state)
                )
                result.append((item.callnumber, state))
            count += 1
        return result

        self.logger.log_info("Worker thread finished")
        # teminate thread


class Mailer(Ui_eMailPreview):
    updateSignal = Signal(int)

    def __init__(self, data=None, parent=None):
        super(QThread).__init__()
        super(Ui_eMailPreview).__init__()

        self.logger = MyLogger("Mailer")
        self.data = data
        self.appid = data["app_id"]
        self.appname = data["app_name"]
        self.subject = data["app_subject"]
        self.profname = data["prof_name"]
        self.mail_data = ""
        self.prof_mail = data["prof_mail"]
        self.dialog = QtWidgets.QDialog()
        self.comboBox.currentIndexChanged.connect(self.set_mail)
        self.prof_name.setText(self.prof_name)
        self.mail_name.setText(self.prof_mail)
        self.load_mail_templates()
        self.gender_female.clicked.connect(self.set_mail)
        self.gender_male.clicked.connect(self.set_mail)
        self.gender_non.clicked.connect(self.set_mail)
        self.buttonBox.accepted.connect(self.createAndSendMail)

    def load_mail_templates(self):
        # print("loading mail templates")
        mail_templates = os.listdir("mail_vorlagen")
        for template in mail_templates:
            self.comboBox.addItem(template)

    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()
        email_header = email_template.split(".eml")[0]
        if "{AppNr}" in email_template:
            email_header = email_template.split(".eml")[0]
        email_header = email_header.format(AppNr=self.appid, AppName=self.appname)
        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
        Appname = self.appname
        mail_html = mail_html.format(
            Profname=self.prof_name.text().split(" ")[-1],
            Appname=Appname,
            AppNr=self.appid,
            AppSubject=self.subject,
            greeting=self.get_greeting(),
        )

        self.mail_body.setHtml(mail_html)

    def createAndSendMail(self):
        import smtplib
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText

        smtp_server = config["mail"]["smtp_server"]
        port: int = config["mail"]["port"]
        sender_email = config["mail"]["sender"]
        password = config["mail"]["password"]
        message = MIMEMultipart()
        message["From"] = sender_email
        message["To"] = self.prof_mail
        message["Subject"] = self.mail_header.text()
        mail_body = self.mail_body.toHtml()
        message.attach(MIMEText(mail_body, "html"))
        mail = message.as_string()

        server = smtplib.SMTP_SSL(smtp_server, port)
        # server.starttls()
        # server.auth(mechanism="PLAIN")
        if config["mail"]["use_user_name"] == 1:
            # print(config["mail"]["user_name"])
            server.login(config["mail"]["user_name"], password)
        else:
            server.login(sender_email, password)
        server.sendmail(sender_email, self.prof_mail, mail)
        # print("Mail sent")
        # end active process
        server.quit()


class MailThread(QThread):
    updateSignal = Signal(int)

    def __init__(self, data=None, parent=None):
        super(QThread).__init__()
        super(MailThread).__init__()
        self.logger = MyLogger("MailThread")
        self.data = data

    def show_ui(self):
        self.mailer = Mailer()
        self.mailer.__init__()
        self.mailer.dialog.exec_()
        self.mailer.dialog.show()

    def run(self):
        self.show_ui()
        self.updateSignal.emit(1)
