from PySide6.QtCore import Signal, QSortFilterProxyModel
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTabWidget, QTableView, QMdiSubWindow, \
    QHeaderView

from gui.model_config import KontorModelConfig
from gui.table_model import KontorTableModel


class ComicWindow(QMdiSubWindow):
    closed = Signal()

    def __init__(self, main_window):
        super().__init__()
        self.data_views = list()
        self._main_window = main_window
        self.log = main_window.log
        self._init_gui()
        self.tick = main_window.tick
        self.cross = main_window.cross

    def _init_gui(self):
        self.setWindowTitle("Comics")
        self.setWidget(QWidget())
        layout = QVBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.addTab(self.generate_data_tab("comic"), "Comics")
        self.tabs.addTab(self.generate_data_tab("publisher"), "Publisher")
        self.tabs.currentChanged.connect(self._tab_changed)
        layout.addWidget(self.tabs)
        self.setLayout(layout)
        self.setWidget(self.tabs)

    def closeEvent(self, event):
        self.closed.emit()
        super().closeEvent(event)
        self._main_window.remove_sub_window('comic')

    def refresh(self):
        # self.log.info("refresh")
        self.data_views[self.tabs.currentIndex()].refresh()

    def _tab_changed(self, tab_index):
        self.data_views[tab_index].refresh()

    def update_status(self, message):
        self._main_window.update_status(message)

    def generate_data_tab(self, table_name):
        data_tab = QWidget()

        table_config = KontorModelConfig(self._main_window.kontor_db, self, table_name)
        model = KontorTableModel(table_config)
        layout = QVBoxLayout()
        self.data_views.append(model)
        data_tab.setLayout(layout)
        table_view = QTableView()
        header = table_view.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        proxy_model = QSortFilterProxyModel()
        proxy_model.setSourceModel(model)
        table_view.setSortingEnabled(True)
        table_view.setModel(proxy_model)
        layout.addLayout(table_config.get_filter_layout())
        layout.addWidget(table_view)
        model.refresh()
        return data_tab
