from .dialog_sources.documentprint_ui import Ui_Dialog
from PyQt6 import QtWidgets, QtCore
from src import Icon

from src.utils.richtext import SemapSchilder, SemesterDocument
from src.backend import Semester, Database
from natsort import natsorted


class DocumentPrintDialog(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(Icon("print").icon)
        self.frame.hide()

        self.semester = Semester()

        self.db = Database()

        self.insert_table_data()
        self.expertMode.clicked.connect(self.enable_expert_mode)
        # Ensure the signal is connected only once
        try:
            self.pushButton_2.clicked.disconnect()
        except TypeError:
            pass  # Signal was not connected before
        self.pushButton_2.clicked.connect(self.on_pushButton_2_clicked)

        try:
            self.pushButton.clicked.disconnect()
        except TypeError:
            pass
        self.pushButton.clicked.connect(self.on_pushButton_clicked)

        try:
            self.btn_load_current_apparats.clicked.disconnect()
        except TypeError:
            pass
        self.btn_load_current_apparats.clicked.connect(self.load_current_clicked)

        try:
            self.manualCheck.clicked.disconnect()
        except TypeError:
            pass
        self.manualCheck.clicked.connect(self.manual_request)

    def manual_request(self):
        self.tableWidget.setRowCount(0)
        request_text = self.textBrowser.toPlainText()
        data = self.db.query_db(request_text)
        apparats: list[str] = []
        if not data:
            self.tableWidget.setRowCount(0)
            return
        for row in data:
            apparats.append(f"{row[0]}")

        self.tableWidget.setHorizontalHeaderLabels(["", "Semesterapparat"])
        self.tableWidget.setColumnWidth(0, 50)
        for entry in apparats:
            # insert the entry, column 1 should be a checkbox, column 2 the data
            self.tableWidget.insertRow(0)
            self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem(""))
            checkbox = QtWidgets.QCheckBox()

            self.tableWidget.setCellWidget(0, 0, checkbox)

            self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(entry))
            # align row 0 column 0 to center

    def load_current_clicked(self):
        entries = self.get_valid_apparats_for_signs()
        self.tableWidget.setHorizontalHeaderLabels(["", "Semesterapparat"])
        self.tableWidget.setColumnWidth(0, 50)
        self.tableWidget.setRowCount(0)
        for entry in entries:
            # insert the entry, column 1 should be a checkbox, column 2 the data
            self.tableWidget.insertRow(0)
            self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem(""))
            checkbox = QtWidgets.QCheckBox()

            self.tableWidget.setCellWidget(0, 0, checkbox)

            self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(entry))

    def enable_expert_mode(self):
        # if self.exportMode.
        if self.expertMode.isChecked():
            self.frame.show()
            self.expertMode.setText("Expertenmodus deaktivieren")
        else:
            self.frame.hide()
            self.expertMode.setText("Expertenmodus aktivieren")

    def on_pushButton_2_clicked(self):
        # get the checked items from the table
        checked_items = []
        for i in range(self.tableWidget.rowCount()):
            checkbox = self.tableWidget.cellWidget(i, 0)
            if isinstance(checkbox, QtWidgets.QCheckBox) and checkbox.isChecked():
                item = self.tableWidget.item(i, 1)
                if item is not None:
                    checked_items.append(item.text())
        document = SemapSchilder(checked_items)
        document.send

    def on_pushButton_clicked(self):
        apparats: list[tuple[int, str]] = []
        apps = self.db.getAllAparats(0)
        apps = natsorted(apps, key=lambda x: x[4], reverse=True)
        for app in apps:
            prof = self.db.getProfById(app[2])
            data = (app[4], f"{prof.lastname} ({app[1]})")
            apparats.append(data)
        SemesterDocument(
            semester=self.semester.value,
            filename="Semesterapparat",
            full=True,
            apparats=apparats,
        )

    def insert_table_data(self):
        entries = self.get_valid_apparats_for_signs()
        self.tableWidget.setHorizontalHeaderLabels(["", "Semesterapparat"])
        self.tableWidget.setColumnWidth(0, 50)
        for entry in entries:
            # insert the entry, column 1 should be a checkbox, column 2 the data
            self.tableWidget.insertRow(0)
            self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem(""))
            checkbox = QtWidgets.QCheckBox()

            self.tableWidget.setCellWidget(0, 0, checkbox)

            self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(entry))
            # align row 0 column 0 to center

    def get_valid_apparats_for_signs(self):
        this_sem = self.db.query_db(
            query="SELECT prof.lname || ' (' || semesterapparat.name || ')' AS formatted_result from semesterapparat INNER JOIN prof ON semesterapparat.prof_id = prof.id WHERE (erstellsemester = ? OR erstellsemester = ?) AND semesterapparat.deletion_status=0",
            args=(str(self.semester.value), str(self.semester.previous)),
        )
        apparats: list[str] = []
        for row in this_sem:
            apparats.append(f"{row[0]}")
        return apparats


def launch():
    app = QtWidgets.QApplication([])
    dialog = DocumentPrintDialog()
    dialog.show()
    app.exec()
