from .DbManager import DbManager
from ..PyqcrmFlags import PyqcrmFlags
from ..Vermasseln import Vermasseln
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput
from .UserDAO import UserDAO
from PySide6.QtCore import Slot, QObject, Signal, QUrl


class UserManager(QObject):

    loginOkay = Signal()

    def __init__(self, user_config = None, role = None):
        super().__init__()
        self.__con = DbManager().getConnection()
        self.__cur = self.__con.cursor()
        if user_config and role:

            self.__username = user_config["PYQCRM_USER"]
            self.__password = user_config["PYQCRM_USER_PASS"]
            self.__info = user_config["PYQCRM_USER_INFO"]
            self.__role = role if role == PyqcrmFlags.ADMIN else 0


    def createUser(self):
        self.__hashPassword()
        user_created = UserDAO().createUser(self.__username, self.__password, self.__info, self.__role)

        return user_created

    def __hashPassword(self):
        self.__password = Vermasseln.userPasswordHash(self.__password)

    def checkAdmin(self):
        self.__cur.callproc("checkAdmin")
        result = self.__cur.fetchall()
        return result

    def getUser(self):
        pass

    def getUsers(self):
        pass

    def delUser(self):
        pass

    def updateUser(self):
        pass

    def disableUser(self):
        pass

    @Slot(str, str)
    def login(self, username, password):
        user = UserDAO().getUser(username)
        if user:
            self.__checkPassword(password, user[2])
        else:
            player = QMediaPlayer(self)
            audioOutput = QAudioOutput(self)
            player.setAudioOutput(audioOutput)
            player.setSource(QUrl("qrc:/sounds/fail2c.ogg"))
            audioOutput.setVolume(150)
            player.play()

    def __checkPassword(self, password, hash_password):
        pw_list = hash_password.split("$")

        hash_pw = Vermasseln.userPasswordHash(password, pw_list[0])
        if hash_password == hash_pw:
            self.loginOkay.emit()



