from PyQt6 import QtWidgets
from PyQt6.QtCore import pyqtSignal
from .widget_sources.Ui_admin_create_user import Ui_Dialog
from src.backend import AdminCommands, Database


class UserCreate(QtWidgets.QDialog, Ui_Dialog):
    admin_action_changed = pyqtSignal()

    def __init__(self):
        super(UserCreate, self).__init__()
        self.setupUi(self)

        self.user_frame_addUser.clicked.connect(self.add_user)
        self.db = Database()
        self.roles = self.db.getRoles()

        self.user_frame_userrole.addItems(self.roles)
        self.user_frame_userrole.addItem("")
        self.user_frame_userrole.setCurrentText("")

        # Variables

    def add_user(self):
        username = self.user_create_frame_username.text()
        password = self.user_create_frame_password.text()
        role = self.user_frame_userrole.currentText()
        if self.db.checkUsername(username):
            return
        userdata = AdminCommands().create_password(password)
        self.db.createUser(
            user=username,
            password=f"{userdata[1]}{userdata[0]}",
            salt=userdata[1],
            role=role,
        )
        if role not in self.roles:
            self.roles.append(role)
            self.user_frame_userrole.addItem(role)
        self.user_create_frame_username.clear()
        self.user_create_frame_password.clear()
        self.admin_action_changed.emit()


def launch():
    app = QtWidgets.QApplication([])
    window = UserCreate()
    window.show()
    app.exec()
