from PyQt6 import QtWidgets

from src.backend import AutoAdder


from .dialog_sources.Ui_parsed_titles import Ui_Form


class ParsedTitles(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.signatures = []
        self.returned = []
        self.prof_id = None
        self.app_id = None
        self.worker = None

    def populate_table(self):
        for i in range(len(self.signatures)):
            self.listWidget.addItem(QtWidgets.QListWidgetItem())
            self.listWidget.item(i).setText(self.signatures[i])
        self.listWidget.item(i).setToolTip("Daten werden gesammelt")

    def update_progress_bar(self, value: int):
        self.progressBar.setValue(value)

    def worker_quit(self):
        # print("Terminating worker")
        self.worker.terminate()
        self.worker.quit()
        self.worker.deleteLater()
        self.worker = None

    def start(self):
        logger.info("Starting AutoAdder")

        self.worker = AutoAdder(
            data=self.signatures,
            app_id=self.app_id,
            prof_id=self.prof_id,
        )
        self.worker.finished.connect(self.on_completion)
        self.worker.updateSignal.connect(self.update_progress_bar)
        self.worker.setTextSignal.connect(self.update_lists)
        self.worker.progress.connect(self.determine_progress)
        self.worker.finished.connect(self.worker.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        # self.worker.updateSignal.connect(self.update_progress_label)
        # worker.finished.connect(worker.deleteLater)

        self.worker.start()

    def on_completion(self):
        logger.info("AutoAdder finished")
        logger.info("Returning data")

    # create a function that closes the dialog

    def determine_progress(self, signal):
        # check length of listWidget
        length = self.listWidget.count()
        # print(f"Length of listWidget: {length}")
        if length == 0:
            logger.info("AutoAdder finished")
            self.buttonBox.accepted.emit()

    def update_lists(self, signal):
        # get text of first entry in listWidget
        text = self.listWidget.item(0).text()
        # remove first entry
        self.listWidget.takeItem(0)
        # add first entry to listWidget_done
        self.listWidget_done.addItem(text)
