from logic import actions

from gui.signal_mgt import SignalManagement
from gui.ui_init import Ui_Initialization
from gui.ui_base import Ui_MainWindow

from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtGui import QStandardItemModel, QStandardItem

class Ui_Library(Ui_MainWindow):
    ##### Méthode de mise à jour de la liste des titres avec QTSignal

    def setupUi(self, MainWindow):
        super().setupUi(MainWindow)
        ui_init = Ui_Initialization(self)
        ui_init.connect_button()
        ui_init.fulfill_list()
        
        self.signal_mgt = SignalManagement(self)
        self.signal_mgt.connect_signals()

    def record_book(self):
        title   = self.title_input.text()
        author  = self.author_input.text()
        message = actions.register_book(title, author)
        QMessageBox.information(None, "Nouvel enregistrement", message)
        # self.refresh_title_list()
        self.signal_mgt.change_list_signal.emit()

    def delete_book(self):
        title = self.title_list.currentText()
        message = actions.delete_book(title)
        QMessageBox.information(None, "Suppression confirmée", message)
        # self.refresh_title_list()
        self.signal_mgt.change_list_signal.emit()

    def refresh_title_list(self):
        self.title_list.clear()
        self.title_list.addItems(actions.list_titles())

    def search_book(self):
        word = self.search_input.text()
        if len(word) == 1:
            results = actions.search_by_letter(word)
            self.display_list_view(results)
            return
        if len(word) > 1:
            results = actions.search_by_word(word)
            self.display_list_view(results)
            return
        
    def display_list_view(self, results):
        self.model = QStandardItemModel()
        self.results_view.setModel(self.model)
        if isinstance(results, str):
            self.model.appendRow(QStandardItem(results))
        else:
            for book in results:
                self.model.appendRow(QStandardItem(str(book)))