from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Slot, Signal
from .ObjectDAO import ObjectDAO
from ..ConfigLoader import ConfigLoader
import re
import json

class ObjectModel(QAbstractTableModel):
    objectAdded = Signal(bool, int)
    objectIdReady = Signal(int)

    __data = None
    __object_dao = None
    __visible_index = None
    __visible_columns = None
    __col_name = ""
    __employee_dao = None
    __col_skip = 2
    __everyone = True


    def __init__(self):
        super().__init__()
        self.__object_dao = ObjectDAO()
        self.__object_dao.newObjectAdded.connect(self.__refreshView)
        self.__conf = ConfigLoader().getConfig()
        self.__key = self.__conf['pyqcrm']['ENCRYPTION_KEY']
        self.__object_dao.newObjectAdded.connect(self.objectAdded)
        self.__getData()

    @Slot(dict)
    def addObject(self, new_object):
        #print(new_object)

        o = self.__object_dao.addObject(new_object)
        self.objectIdReady.emit(o)

    # @Slot(str)
    # def viewCriterion(self, criterion, processed = False, fired = False):
    #     self.__getData(criterion, processed, fired)

    @Slot()
    def __refreshView(self):
        self.__getData()

    def __getData(self, criterion = "Alle"):
        self.beginResetModel()
        rows, self.__visible_columns = self.__object_dao.getObjects(criterion, self.__key)
        self.__data = rows
        self.endResetModel()

    def rowCount(self, parent= QModelIndex()):
        return len (self.__data)

    def columnCount(self, parent= QModelIndex()):
        return len(self.__visible_columns) - self.__col_skip

    @Slot(str)
    def viewCriterion(self, criterion):
        self.__getData(criterion)

    def data(self, index, role= Qt.DisplayRole):
        if role == Qt.DisplayRole:
            row = self.__data[index.row()]
            object_col = index.column() + self.__col_skip
            tr = row[object_col] #if type(row[index.column() + 2]) is str else str(row[index.column() + 2], "utf-8")
            if object_col > 4 and tr:
                tr = re.sub("Keine Angabe ","", tr)
            return tr
        return None

    def headerData(self, section, orientation, role = Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            self.__col_name = self.__visible_columns[section + self.__col_skip]
            return self.__col_name
        return super().headerData(section, orientation, role)

    @Slot(int)
    def onRowClicked(self, row):
        #print(self.__data)
        print(f"Selected table row: {row}, corresponding DB ID: {self.__data[row][0]}")
        #if not self.__employee_dict['employee'] or self.__data[row][0] != self.__employee_dict['employee']['id']:
            #self.__employee = self.__employee_dao.getEmployee(self.__data[row][0], self.__key)
            #print(self.__business)
            #self.__getEmployeeInfo()
            # self.__getContactInfo()
            # print(self.__business_dict)
