from PyQt6 import QtCore, QtGui, QtWidgets

from .dialog_sources.Ui_medianadder import Ui_Dialog
from src import Icon


class MedienAdder(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setupUi(self)
        self.setWindowIcon(Icon("edit").icon)
        self.setWindowTitle("Medien hinzufügen")
        self.color_table()
        self.mode = ""
        self.data = []
        self.use_any = False
        self.use_exact = False
        self.lineEdit.returnPressed.connect(self.add_signature)
        self.btn_cancel.clicked.connect(self.close)
        self.btn_save.clicked.connect(self.send_data)
        # disable button box button okay
        self.btn_save.setEnabled(False)
        self.check_use_exact_signature.clicked.connect(self.check_use_exact)
        self.check_use_any_book.clicked.connect(self.check_use_any)

    def check_use_exact(self):
        self.use_exact = self.check_use_exact_signature.isChecked()

    def check_use_any(self):
        self.use_any = self.check_use_any_book.isChecked()

    def enable_button(self):
        if self.listWidget.count() > 0:
            self.btn_save.setEnabled(True)
        else:
            self.btn_save.setEnabled(False)

    def add_signature(self):
        signature = self.lineEdit.text()
        self.listWidget.addItem(signature.strip())
        self.lineEdit.clear()
        self.list_amount.setText(str(self.listWidget.count()))
        self.enable_button()

    def get_list_data(self) -> list:
        signatures = self.listWidget.findItems("*", QtCore.Qt.MatchFlag.MatchWildcard)
        return [signature.text() for signature in signatures]

    def get_mode(self) -> str:
        return self.comboBox.currentText()

    def send_data(self):
        self.mode = self.get_mode()
        self.data = self.get_list_data()
        self.accept()

    def color_table(self):
        # set tree cells to red, if it is 0, to green if it is 1. remove digits after comma
        for row in range(self.tableWidget.rowCount()):
            for col in range(self.tableWidget.columnCount()):
                item = self.tableWidget.item(row, col)
                if item is not None:
                    if item.text() == "0":
                        item.setBackground(QtGui.QColor("red"))
                        item.setText("")

                    elif item.text() == "1":
                        item.setBackground(QtGui.QColor("green"))
                        item.setText("")

                    else:
                        item.setText(item.text().split(".")[0])


def launch_gui():
    app = QtWidgets.QApplication([])
    dialog = MedienAdder()
    dialog.show()
    app.exec()
    # print(dialog.mode, dialog.data, dialog.result())
