from PySide6.QtCore import QSortFilterProxyModel
from PySide6.QtWidgets import QHBoxLayout, QWidget, QTableView, QVBoxLayout, QFormLayout, QLineEdit, QLabel

from .table_model import KontorTableModel


class KontorTableDetailsView:
    def __init__(self, table_model: KontorTableModel):
        self._data_view: QWidget = QWidget()
        self._model = table_model
        self.log = table_model.log
        self._table_view = QTableView()
        self._label = QLabel()
        self.init_gui()

    def init_gui(self):
        self.log.info("KontorTableDetailsView.init_gui()")
        layout = QVBoxLayout()
        self._data_view.setLayout(layout)
        details_layout = QHBoxLayout()
        table_with_details = QWidget()
        table_with_details.setLayout(details_layout)

        self._table_view.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
        proxy_model = QSortFilterProxyModel()
        proxy_model.setSourceModel(self._model)
        self._table_view.setSortingEnabled(True)
        self._table_view.setModel(proxy_model)
        self._table_view.clicked.connect(self.update_details)
        self._table_view.activated.connect(self.refresh_details)

        layout.addLayout(self._model.config.get_filter_layout())
        details_layout.addWidget(self._table_view)

        form = QWidget()
        form_layout = QFormLayout(form)
        form.setLayout(form_layout)

        title = QLineEdit(form)
        form_layout.addRow("ID", self._label)
        form_layout.addRow("Title", title)
        # layout.addWidget(table_view)
        details_layout.addWidget(form)
        layout.addWidget(table_with_details)
        self._model.refresh()
        self._table_view.resizeColumnToContents(0)

    @property
    def data_view(self):
        return self._data_view

    def update_details(self, item):
        print(f"Cell {item.row()}-{item.column()} selected")
        self.log.info(f"Cell {item.row()}-{item.column()} selected")
        self._label.setText(self._model.raw_data()[item.row()][0])

    def refresh_details(self):
        indexes = self._table_view.selectedIndexes()
        for index in indexes:
            self.log.info(f"refresh_details: Cell {index.row()}-{index.column()} selected")
