from .widget_sources.Ui_admin_edit_user import Ui_Dialog
from PyQt6 import QtWidgets
from src.backend import Database
from src.backend import AdminCommands

admin = AdminCommands()


class EditUser(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super(EditUser, self).__init__()
        self.setupUi(self)
        self.btn_delete_user.clicked.connect(self.delete_user)
        self.update_user.clicked.connect(self.update_user_data)
        self.user_delete_frame_user_select.currentIndexChanged.connect(self.updateData)
        # Variables
        self.db = Database()
        self.users = self.db.getUsers()
        for user in self.users:
            self.user_delete_frame_user_select.addItem(user[2])
            self.user_edit_frame_role_select.addItem(user[5])

    def updateData(self):
        role = self.users[self.user_delete_frame_user_select.currentIndex()][5]
        self.user_edit_frame_role_select.setCurrentText(role)
        if role == "admin":
            self.user_edit_frame_role_select.setEnabled(False)
            self.btn_delete_user.setEnabled(False)
            self.btn_delete_user.setToolTip("Admins cannot be deleted")
        else:
            self.user_edit_frame_role_select.setEnabled(True)
            self.btn_delete_user.setEnabled(True)

    def update_user_data(self):
        username = self.user_delete_frame_user_select.currentText()
        password = (
            self.user_edit_frame_new_password.text()
            if self.user_edit_frame_new_password.text() != ""
            else None
        )
        role = (
            self.user_edit_frame_role_select.currentText()
            if self.user_edit_frame_role_select.currentText() != ""
            else None
        )

        userdata = admin.create_password(password)
        data = {
            "password": f"{userdata[1]}{userdata[0]}",
            "salt": userdata[1],
            "role": role,
        }
        data = {key: value for key, value in data.items() if value is not None}
        # print(data)
        self.db.updateUser(username=username, data=data)
        self.user_delete_frame_user_select.setCurrentText("")
        self.user_edit_frame_new_password.clear()
        self.user_edit_frame_role_select.setCurrentText("")

    def delete_user(self):
        if self.user_delete_confirm.isChecked():
            username = self.user_delete_frame_user_select.currentText()
            self.db.deleteUser(username)
            self.user_delete_frame_user_select.removeItem(
                self.user_delete_frame_user_select.currentIndex()
            )
            self.user_delete_confirm.setChecked(False)
        else:
            pass
