from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Slot, QObject, Signal
from .ContactDAO import ContactDAO
from ..ConfigLoader import ConfigLoader
import logging

class ContactModel(QObject):
    contactIdReady = Signal(int)
    objectContactAdded = Signal(bool)

    __contact = None
    __contact_dict = {'contact':{}}

    def __init__(self):
        super().__init__()
        # print(f"*** File: {__file__}, __init__()")
        #self.logger = logging.getLogger()
        self.__conf = ConfigLoader().getConfig()
        self.__key = self.__conf['pyqcrm']['ENCRYPTION_KEY']
        self.__contact_dao = ContactDAO()
        self.__contact_dao.newObjectContactAdded.connect(self.objectContactAdded)
        self.__data = self.__getData()

    def getContacts(self):
        # print(f"*** File: {__file__}, getContacts()")
        logging.debug("No debug message")
        return self.__data

    def __getData(self):
        # print(f"*** File: {__file__}, __getData()")
        ContactDAO().getContacts()

    @Slot(dict)
    def addContact(self, contact):
        i = ContactDAO().addContact(contact, self.__key)
        self.contactIdReady.emit(i)

    @Slot(dict, int)
    def addObjectContact(self, contact, objectid):
        ContactDAO().addObjectContact(contact, objectid, self.__key)
        #self.contactIdReady.emit(i)

    def __getContact(self, contact):
        self.__contact = ContactDAO().getContact(contact, self.__key)
        self.__getContactInfo()

    @Slot(int, result = dict)
    def getContactDetails(self, contact):
        self.__getContact(contact)
        #print(self.__contact_dict)
        return self.__contact_dict

    def __getContactInfo(self):
        self.__contact_dict['contact']['id'] = self.__contact[0][0]
        self.__contact_dict['contact']['salute'] = self.__contact[0][1]
        self.__contact_dict['contact']['fname'] = self.__contact[0][2].decode("utf-8")
        self.__contact_dict['contact']['lname'] = self.__contact[0][3].decode("utf-8")
        self.__contact_dict['contact']['phone'] = self.__contact[0][4].decode("utf-8")
        self.__contact_dict['contact']['cell'] = self.__contact[0][5].decode("utf-8")
        self.__contact_dict['contact']['position'] = self.__contact[0][6]
        self.__contact_dict['contact']['email'] = self.__contact[0][7].decode("utf-8")
        self.__contact_dict['contact']['birthday'] = self.__contact[0][8].decode("utf-8")
        self.__contact_dict['contact']['priority'] = "Ja" if self.__contact[0][9]  else "Nein"
        self.__contact_dict['contact']['invoice'] = "Ja" if self.__contact[0][10] else "Nein"
        self.__contact_dict['contact']['reminder'] = "Ja" if self.__contact[0][11] else "Nein"



