import time

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

from src.backend.database import Database

from src.logic.webrequest import BibTextTransformer, WebRequest

# from src.transformers import RDS_AVAIL_DATA


class AvailChecker(QThread):
    updateSignal = Signal(str, int)
    updateProgress = Signal(int, int)

    def __init__(
        self, links: list = None, appnumber: int = None, parent=None, books=list[dict]
    ):
        if links is None:
            links = []
        super().__init__(parent)
        logger.info("Starting worker thread")
        logger.info(
            "Checking availability for "
            + str(links)
            + " with appnumber "
            + str(appnumber)
            + "..."
        )
        self.links = links
        self.appnumber = appnumber
        self.books = books
        logger.info(
            f"Started worker with appnumber: {self.appnumber} and links: {self.links} and {len(self.books)} books..."
        )
        time.sleep(2)

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

            book_id = None
            for item in rds.items:
                sign = item.superlocation
                loc = item.location
                # # print(item.location)
                if self.appnumber in sign or self.appnumber in loc:
                    state = 1
                    break
            for book in self.books:
                if book["bookdata"].signature == link:
                    book_id = book["id"]
                    break
            logger.info(f"State of {link}: " + str(state))
            # print("Updating availability of " + str(book_id) + " to " + str(state))
            self.db.setAvailability(book_id, state)
            count += 1
            self.updateProgress.emit(count, len(self.links))
            self.updateSignal.emit(item.callnumber, state)

        logger.info("Worker thread finished")
        # teminate thread

        self.quit()
