from __future__ import annotations

import dataclasses
from pathlib import Path

import axipy
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QDialog, QPushButton, QDialogButtonBox, QListWidgetItem, QAbstractItemView
from .ui import Ui_DialogChooseOpenedTables
from .utils import is_tab_table


class DialogChooseOpenedTables(QDialog, Ui_DialogChooseOpenedTables):
    @dataclasses.dataclass
    class Result:
        tab_files: list[Path] | None = None

    def __init__(self, plugin: axipy.Plugin, result: Result) -> None:
        super().__init__(axipy.view_manager.global_parent)
        self.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose, True)

        self.plugin = plugin
        self.__result = result

        self.list_widget_tables.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)

        for tab_table in filter(is_tab_table, axipy.data_manager.tables):
            item = QListWidgetItem(tab_table.name)
            item.setData(Qt.UserRole, tab_table.file_name)
            self.list_widget_tables.addItem(item)

        # Check if there are any items in the QListWidget
        if self.list_widget_tables.count() > 0:
            # Select the first item
            self.list_widget_tables.setCurrentRow(0)

        self._ui_ok.setText(self.plugin.tr("Добавить"))

    @property
    def _ui_ok(self) -> QPushButton:
        return self.buttonBox.button(QDialogButtonBox.Ok)

    @property
    def _ui_cancel(self) -> QPushButton:
        return self.buttonBox.button(QDialogButtonBox.Cancel)

    def done(self, return_code: int) -> None:
        if return_code == self.Accepted:
            paths = [elem.data(Qt.UserRole) for elem in self.list_widget_tables.selectedItems()]
            self.__result.tab_files = paths

        super().done(return_code)
