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

from .model_config import KontorModelConfig
from .table_details import KontorTableDetailsView
from .table_model import KontorTableModel


class MediaWindow(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("Media")
        self.setWidget(QWidget())
        layout = QVBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.addTab(self.generate_data_tab("media_file"), "Media File")
        self.tabs.addTab(self.generate_data_tab("media_video"), "Media Video")
        self.tabs.addTab(self.generate_data_tab("media_article"), "Media Article")
        self.tabs.addTab(self.generate_data_tab_with_details("media_actor"), "Media Actor")
        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('media')

    def refresh(self):
        self.log.info("MediaWindow.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()
        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()
        table_view.resizeColumnToContents(0)
        return data_tab

    def generate_data_tab_with_details(self, table_name):
        table_config = KontorModelConfig(self._main_window.kontor_db, self, table_name)
        model = KontorTableModel(table_config)
        self.data_views.append(model)
        details_view = KontorTableDetailsView(model)
        return details_view.data_view

    def cell_selected(self, item):
        self.log.info(f"Cell {item.row()}:{item.column()} clicked")
