from PySide6.QtWidgets import QHBoxLayout, QCheckBox
from kontor_schema import KontorDB, ColumnEntry


class KontorModelConfig:

    def __init__(self, kontor_db: KontorDB, main_window, table_name: str):
        self.header = {}
        self.filter = {}
        self.main_window = main_window
        self.log = main_window.log
        self._table_name = table_name
        self.kontor_db = kontor_db
        self.get_table_config()

    def __str__(self):
        return f"KontorModelConfig({self._table_name})"

    def get_table_config(self):
        # self.log.info("get_table_config %s", self)
        self.header = self.kontor_db.get_column_meta_data(self._table_name)
        self.filter = self.kontor_db.get_filters(self._table_name)
        # self.log.info("headers: %s", self.header)
        # self.log.info("%s filters: %s", self, self.filter)

    def filters(self) -> dict:
        # self.log.info("%s filters: %s", self, self.filter)
        _filters = {}
        # print(self.filter["download"].isChecked())
        for column, filter_info in self.filter.items():
            # print(column, filter_info)
            if filter_info[ColumnEntry.COLUMN_WIDGET].isChecked():
                _filters[column] = True
        # print(f"{filter_rule=}")
        # self.log.info("filters -> %s", _filters)
        return _filters

    def get_data(self) -> list:
        # self.log.info("get_data")
        data = self.kontor_db.data(self._table_name, self.header, self.filters())
        # self.log.info("get_data: %d  %s", len(data), data)
        return data

    def get_filter_layout(self) -> QHBoxLayout:
        # self.log.info("get_filter_layout: %s", self.filter)
        filter_layout = QHBoxLayout()
        for column, filter_info in self.filter.items():
            filter_checkbox = QCheckBox()
            filter_checkbox.setText(filter_info[ColumnEntry.COLUMN_LABEL])
            filter_checkbox.checkStateChanged.connect(self.main_window.refresh)
            self.filter[column][ColumnEntry.COLUMN_WIDGET] = filter_checkbox
            filter_layout.addWidget(filter_checkbox)
        filter_layout.addStretch()
        # self.log.info("get_filter_layout: %s", self.filter)
        return filter_layout
