from typing import List

from PySide6 import QtWidgets
from PySide6.QtCore import Qt

from src.logic import BookData

from .widget_sources.new_edition_check_book_ui import (
    Ui_Dialog as Ui_NewEditionCheckBook,
)
from .widget_sources.new_edition_check_found_result_ui import (
    Ui_Dialog as Ui_NewEditionCheckFoundResult,
)
from .widget_sources.new_edition_check_ui import Ui_Dialog as Ui_NewEditionCheck


class NewEditionCheckFoundResult(QtWidgets.QDialog, Ui_NewEditionCheckFoundResult):
    def __init__(self, book: BookData, parent=None):
        assert isinstance(book, BookData)
        super().__init__(parent)
        self.setupUi(self)
        self.book = book
        self.line_ppn.setText(self.book.ppn if self.book.ppn else "")
        self.line_title.setText(self.book.title if self.book.title else "")
        self.line_signature.setText(self.book.signature if self.book.signature else "")
        self.line_edition.setText(self.book.edition if self.book.edition else "")
        self.line_publisher.setText(self.book.publisher if self.book.publisher else "")
        self.line_year.setText(self.book.year if self.book.year else "")
        self.line_pages.setText(self.book.pages if self.book.pages else "")
        link = self.book.link if self.book.link else ""
        if self.book.link != "SWB":
            link = f"<a href='{link}'>Lehmanns</a>"
        self.line_source.setText(link)
        self.line_source.setOpenExternalLinks(True)
        self.line_source.setTextFormat(Qt.TextFormat.RichText)
        self.line_source.setTextInteractionFlags(
            Qt.TextInteractionFlag.TextBrowserInteraction
        )
        self.line_isbn.setText(
            ", ".join(self.book.isbn)
            if isinstance(self.book.isbn, list)
            else self.book.isbn
        )
        if (
            self.book.link == "SWB"
            and self.book.signature is not None
            and self.book.signature != ""
        ):
            self.in_library.setText(
                "Diese Neuauflage ist bereits in der Bibliothek vorhanden."
            )
            self.book.library_location = 1

    pass


class NewEditionCheckBook(QtWidgets.QDialog, Ui_NewEditionCheckBook):
    def __init__(self, book: BookData, responses: List[BookData], parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.book = book
        self.accepted_books = []
        self.responses = responses
        self.line_author.setText(self.book.author)
        self.line_title.setText(self.book.title)
        self.line_ppn.setText(self.book.ppn if self.book.ppn else "")
        self.line_signature.setText(self.book.signature if self.book.signature else "")
        self.line_edition.setText(self.book.edition if self.book.edition else "")
        self.line_publisher.setText(self.book.publisher if self.book.publisher else "")
        self.line_year.setText(self.book.year if self.book.year else "")
        self.line_pages.setText(self.book.pages if self.book.pages else "")
        self.line_isbn.setText(
            ", ".join(self.book.isbn)
            if isinstance(self.book.isbn, list)
            else self.book.isbn
        )

        for _ in range(self.stackedWidget.count()):
            widget = self.stackedWidget.widget(0)
            self.stackedWidget.removeWidget(widget)
            widget.deleteLater()
        for response in self.responses:
            self.stackedWidget.addWidget(
                NewEditionCheckFoundResult(parent=self, book=response)
            )
        self.label_book_index.setText(f"1 / {self.stackedWidget.count()}")
        self.btn_next.clicked.connect(self.next)
        self.btn_prev.clicked.connect(self.previous)

    def next(self):
        index = self.stackedWidget.currentIndex()
        if index < self.stackedWidget.count() - 1:
            index += 1
            self.stackedWidget.setCurrentIndex(index)
            self.label_book_index.setText(f"{index + 1} / {self.stackedWidget.count()}")
        if index == self.stackedWidget.count() - 1:
            self.btn_next.hide()

    def previous(self):
        index = self.stackedWidget.currentIndex()
        if index > 0:
            index -= 1
            self.stackedWidget.setCurrentIndex(index)
            self.label_book_index.setText(f"{index + 1} / {self.stackedWidget.count()}")
        if index < self.stackedWidget.count() - 1:
            self.btn_next.show()

    pass


class NewEditionChecker(QtWidgets.QDialog, Ui_NewEditionCheck):
    def __init__(self, results, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.results = results
        self.setWindowTitle("Prüfung auf Neuauflagen")
        # remove pages from stacked widget
        for _ in range(self.stackedWidget.count()):
            widget = self.stackedWidget.widget(0)
            self.stackedWidget.removeWidget(widget)
            widget.deleteLater()
        for resultset in self.results:
            book, responses = resultset
            self.stackedWidget.addWidget(
                NewEditionCheckBook(parent=self, book=book, responses=responses)
            )
        self.accepted_books = []
        self.stackedWidget.setCurrentIndex(0)
        self.progressBar.setMaximum(len(self.results))
        self.progressBar.setValue(1)
        self.btn_next.clicked.connect(self.next)
        self.btn_prev.clicked.connect(self.previous)
        self.btn_finish.hide()
        self.btn_finish.clicked.connect(self.accept)
        self.btn_prev.hide()

    def next(self):
        index = self.stackedWidget.currentIndex()
        if index < self.stackedWidget.count() - 1:
            index += 1
            self.stackedWidget.setCurrentIndex(index)
            self.progressBar.setValue(index + 1)
            self.btn_prev.show()
        if index == self.stackedWidget.count() - 1:
            self.btn_next.hide()
            self.btn_finish.show()

    def previous(self):
        index = self.stackedWidget.currentIndex()
        if index > 0:
            index -= 1
            self.stackedWidget.setCurrentIndex(index)
            self.progressBar.setValue(index + 1)

    def accept(self) -> None:
        print("finished checking for new editions")
        accepted_books = []
        for i in range(self.stackedWidget.count()):
            book_widget = self.stackedWidget.widget(i)
            if isinstance(book_widget, NewEditionCheckBook):
                for j in range(book_widget.stackedWidget.count()):
                    found_widget = book_widget.stackedWidget.widget(j)
                    if isinstance(found_widget, NewEditionCheckFoundResult):
                        if found_widget.checkBox.isChecked():
                            accepted_books.append(found_widget.book)
        super().accept()
        print("accepted", len(accepted_books), "new editions")
        self.accepted_books = accepted_books
