from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Slot, Signal
from PySide6.QtQml import QJSValue

from .EmployeeDAO import EmployeeDAO
from ..ConfigLoader import ConfigLoader
import re


class EmployeeModel(QAbstractTableModel):
    addedNewEmployee = Signal(bool)
    __data = None
    __employee_dao = None
    __visible_columns = None
    __col_name = ""
    __col_skip = 2
    __everyone = True

    def __init__(self):
        super().__init__()
        self.__employee_dao = EmployeeDAO() 
        self.__employee_dao.newEmployeeAdded.connect(self.__refreshView)
        self.__conf = ConfigLoader().getConfig()
        self.__key = self.__conf['pyqcrm']['ENCRYPTION_KEY']
        self.__getData()

    @Slot(dict)
    def addEmployee(self, new_employee):
        if 'worklicense' in new_employee:
            new_employee['worklicense'] = int(new_employee['worklicense'])
            new_employee['residencetype'] = int(new_employee['residencetype'])
        self.__employee_dao.addApplicant(new_employee, self.__key, False)

    @Slot(QJSValue)
    def addApplicant(self, applicant: QJSValue):
        self.__employee_dao.addApplicant({
            "city": applicant.property("city").toString(),
            "email": applicant.property("email").toString(),
            "firstname": applicant.property("firstname").toString(),
            "formofaddress": applicant.property("formofaddress").toString(),
            "houseno": applicant.property("houseno").toString(),
            "lastname": applicant.property("lastname").toString(),
            "mobile": applicant.property("mobile").toString(),
            "phone": applicant.property("phone").toString(),
            "postcode": applicant.property("postcode").toInt(),
            "street": applicant.property("street").toString(),
            "title": applicant.property("title").toString(),
        }, self.__key, True)

    @Slot(bool)
    def __refreshView(self, added):
        if added:
            self.__getData()
        self.addedNewEmployee.emit(added)

    def __getData(self, criterion="Alle", processed=False, fired=False, every_state=True):
        self.beginResetModel()
        rows, self.__visible_columns = self.__employee_dao.getEmployees(self.__key, criterion, processed, fired,
                                                                        every_state)
        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.__everyone = criterion == 'Alle'
        self.__col_skip = 2
        self.__getData(criterion, criterion == 'Erledigt', False, criterion == 'Alle')

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole:
            row = self.__data[index.row()]
            applicant_col = index.column() + self.__col_skip
            tr = row[applicant_col]
            if applicant_col == 2 and self.__everyone:
                tr = 'Ja' if tr == 1 else 'Nein'
            else:
                if tr:
                    tr = re.sub("Keine Angabe ", "", tr)
            return tr
        return None

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