from .dialog_sources.Ui_elsa_add_table_entry import Ui_Dialog
from src.logic.webrequest import WebRequest, BibTextTransformer
from src import Icon
from PyQt6 import QtWidgets
from src.transformers.transformers import DictToTable
from src.logic.zotero import ZoteroController

zot = ZoteroController()
dtt = DictToTable()


class ElsaAddEntry(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None, data=None):
        super(ElsaAddEntry, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Eintrag zitieren")
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Ok
        ).clicked.connect(self.accept)
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Cancel
        ).clicked.connect(self.close)
        self.buttonBox.button(
            QtWidgets.QDialogButtonBox.StandardButton.Discard
        ).clicked.connect(self.discard)
        self.mode = None
        self.btn_search.clicked.connect(self.search)
        self.btn_mono.clicked.connect(self.stack)
        self.btn_zs.clicked.connect(self.stack)
        self.btn_hg.clicked.connect(self.stack)
        self.make_quote.clicked.connect(self.display_data)
        self.copy_filename.clicked.connect(
            lambda: self.copy_to_clipboard(self.filename_edit)
        )
        self.copy_ilias_filename.clicked.connect(
            lambda: self.copy_to_clipboard(self.ilias_filename)
        )
        self.copy_qoute.clicked.connect(
            lambda: self.copy_to_clipboard(self.file_desc_edit)
        )
        self.setWindowIcon(Icon("edit").icon)
        self.stackedWidget.setEnabled(False)
        self.btn_hg.setChecked(False)
        tooptip = "Hier die Seiten des Scans eintragen, z.B. 1-10"
        self.page_warn.setToolTip(tooptip)
        self.page_warn_2.setToolTip(tooptip)
        self.page_warn_3.setToolTip(tooptip)
        self.make_quote.setEnabled(False)
        Icon("important_warn", self.page_warn)
        Icon("important_warn", self.page_warn_2)
        Icon("important_warn", self.page_warn_3)
        self.data = None
        self.source_pages = None
        self.book_pages.textChanged.connect(self.check_pages)
        self.hg_pages.textChanged.connect(self.check_pages)
        self.zs_pages.textChanged.connect(self.check_pages)
        self.retryButton.clicked.connect(self.retry)

    def check_pages(self):
        if self.source_pages:
            if self.book_pages.text() != self.source_pages:
                self.make_quote.setEnabled(True)
            elif self.hg_pages.text() != self.source_pages:
                self.make_quote.setEnabled(True)
            elif self.zs_pages.text() != self.source_pages:
                self.make_quote.setEnabled(True)

    def copy_to_clipboard(self, field):
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(field.toPlainText())

    def discard(self):
        for line in self.findChildren(QtWidgets.QLineEdit):
            line.clear()
        for line in self.findChildren(QtWidgets.QTextEdit):
            line.clear()

    def retry(self):
        match self.mode:
            case "book":
                self.stackedWidget.setCurrentIndex(0)
            case "hg":
                self.stackedWidget.setCurrentIndex(1)
            case "zs":
                self.stackedWidget.setCurrentIndex(2)

    def stack(self):
        self.stackedWidget.setEnabled(True)
        if self.btn_mono.isChecked():
            self.stackedWidget.setCurrentIndex(0)
            self.mode = "book"
        elif self.btn_hg.isChecked():
            self.stackedWidget.setCurrentIndex(1)
            self.mode = "hg"
        elif self.btn_zs.isChecked():
            self.stackedWidget.setCurrentIndex(2)
            self.mode = "zs"

    def display_data(self):
        fields = self.findChildren(QtWidgets.QLineEdit)
        # remove all fields from the list if they do not start with the mode and _
        fields = [field for field in fields if field.objectName().startswith(self.mode)]
        data = {}
        for field in fields:
            # get the field name
            fname = field.objectName()
            # get the field data
            fdata = field.text()
            data[fname] = fdata
        data["mode"] = self.mode
        table = dtt.transform(data)

        if data is None:
            return
        res_key = None
        filename = None
        ilias_name = None
        if table["type"] == "zs":
            book = zot.createBook(table["isbn"])
            res_key = zot.createJournalArticle(book, table)
            logger.debug(book)
            a_lastname = table["section_author"].split(";")[0].strip().split(",")[0]
            a_firstname = table["section_author"].split(";")[0].strip().split(",")[1]
            author = f"{a_lastname}, {a_firstname[0]}"
            year = book.date.strip() if book.date != "" else table["year"]
            chapter = table["chapter_title"].strip()
            page = table["pages"].strip()
            if len(book.creators) > 1:
                a_lastname = f"{a_lastname}_etal"
            filename = f"{a_lastname}_{year}_{chapter}_{page}_z.pdf"
            ilias_name = f"{author}. ({year}). {chapter}. S. {page}."
        elif table["type"] == "book":
            book = zot.createBook(table["signature"])
            res_key = zot.createBookSection(book, table)
            a_lastname = book.creators[0]["lastName"].strip()
            a_firstname = book.creators[0]["firstName"].strip()
            author = f"{a_lastname}, {a_firstname[0]}"

            title = book.title.strip()
            year = book.date.strip()
            page = table["pages"].strip()
            if len(book.creators) > 1:
                a_lastname = f"{a_lastname}_etal"
            filename = f"{a_lastname}_{year}_{title}_{page}.pdf"
            ilias_name = f"{author}. ({year}). {title}. S. {page}."
        elif table["type"] == "hg":
            book = zot.createBook(table["signature"])
            res_key = zot.createHGSection(book, table)
            a_lastname = table["section_author"].split(";")[0].strip().split(",")[0]
            a_firstname = (
                table["section_author"].split(";")[0].strip().split(",")[1].strip()[0]
            )
            author = f"{a_lastname}, {a_firstname[0]}"
            editor = table["work_author"].split(";")[0].strip().split(",")[0]
            title = table["chapter_title"].strip()
            year = book.date.strip()
            page = table["pages"].strip()
            s_authors = table["section_author"].split(";")
            s_editors = table["work_author"].split(";")
            if len(s_authors) > 1:
                a_lastname = f"{a_lastname}_etal"
                author = f"{author} et al."
            if len(s_editors) > 1:
                editor = f"{editor}_etal"
            filename = f"{a_lastname}_in_{editor}_{year}_{title}_{page}.pdf"
            ilias_name = f"{author}. ({year}). {title}. S. {page}."
        citation = None
        if res_key:
            citation = zot.get_citation(res_key)
            zot.deleteItem(res_key)
        self.file_desc_edit.setText(citation)
        self.filename_edit.setText(filename.lower())
        self.ilias_filename.setText(ilias_name)
        self.stackedWidget.setCurrentIndex(3)

    def search(self, pages=None):
        print("searching")
        param = self.searchIdent.text()
        web = WebRequest()
        web.get_ppn(param)
        data = web.get_data_elsa()
        # if isinstance(data, list):
        #     data = data[0]
        bib = BibTextTransformer("ARRAY")
        bib.get_data(data)
        data = bib.return_data()
        self.setdata(data, pages)

    def setdata(self, data, pages=None):
        # use field to set data in the correct fields
        fields = self.findChildren(QtWidgets.QLineEdit)
        self.source_pages = data.pages
        # remove all fields from the list if they do not start with the mode and _
        fields = [field for field in fields if field.objectName().startswith(self.mode)]
        for field in fields:
            c_field = field.objectName()
            c_field = f"self.{c_field}"
            # convert c_field string to class element
            c_field = eval(c_field)
            # get the data associated with the field, data is a dataclass
            fname = field.objectName().split("_")[1]
            c_data = f"data.{fname}"
            try:
                c_data = eval(c_data)

            except AttributeError:
                c_data = ""
            if isinstance(c_data, list):
                if c_data != []:
                    c_data = c_data[0]
                else:
                    c_data = ""
            c_field.setText(c_data)
            if "Seiten" in c_field.text():
                self.source_pages = c_field.text()

        if pages:
            self.source_pages = pages
            eval(f"self.{self.mode}_pages").setText(pages)


def launch():
    app = QtWidgets.QApplication([])
    dialog = ElsaAddEntry()
    dialog.show()
    app.exec()
    return dialog.data
