from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QTableView
from PyQt5.QtCore import pyqtSignal, Qt

from nixview.util.file_handler import FileHandler
from nixview.util.dataview import DataView
from nixview.communicator import communicator
from nixview.data_models.table_model import TableModel

class TableScreen(QWidget):
    close_signal = pyqtSignal()

    def __init__(self, parent=None) -> None:
        super().__init__(parent=parent)
        self._file_handler = FileHandler()

        self.table = QTableView()
        self.table.setSortingEnabled(False)
        self.table.setShowGrid(True)

        close_btn = QPushButton("close")
        close_btn.clicked.connect(self.on_close)
        
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(self.table)
        self.layout().addWidget(close_btn)
        self._data_view = None

    def on_close(self):
        self.close_signal.emit()

    def show(self, item):
        try:
            self._data_view = DataView(item, self._file_handler)
        except ValueError as e:
            communicator.table_error.emit("error in tablescreen.show %s" % e)
            return
        if self._data_view is None:
            return
        data_model = TableModel(self._file_handler, self._data_view)
        self.table.setModel(data_model)
