import hashlib

from PyQt6 import QtCore, QtWidgets

from src import Icon, logger
from src.backend.admin_console import AdminCommands
from src.backend.database import Database

from .dialog_sources.Ui_login import Ui_Dialog


class LoginDialog(Ui_Dialog):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(218, 190)
        self.dialog = Dialog
        self.dialog.setWindowIcon(Icon("locked").icon)
        self.login_button = QtWidgets.QPushButton(parent=Dialog)
        self.login_button.setGeometry(QtCore.QRect(30, 140, 76, 32))
        self.login_button.setObjectName("login_button")
        self.login_button.setText("Login")
        self.login_button.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
        self.cancel_button = QtWidgets.QPushButton(parent=Dialog)
        self.cancel_button.setGeometry(QtCore.QRect(120, 140, 76, 32))
        self.cancel_button.setObjectName("cancel_button")
        self.cancel_button.setText("Cancel")
        self.cancel_button.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
        self.cancel_button.clicked.connect(self.cancel_buttonfn)
        self.label = QtWidgets.QLabel(parent=Dialog)
        self.label.setGeometry(QtCore.QRect(20, 40, 71, 21))
        self.label.setObjectName("label")
        self.lineEdit = QtWidgets.QLineEdit(parent=Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(80, 40, 113, 21))
        self.lineEdit.setObjectName("lineEdit")
        # set strong focus to lineEdit
        self.lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
        self.label_2 = QtWidgets.QLabel(parent=Dialog)
        self.label_2.setGeometry(QtCore.QRect(20, 80, 71, 21))
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(parent=Dialog)
        self.lineEdit_2.setGeometry(QtCore.QRect(80, 80, 113, 21))
        self.lineEdit_2.setInputMethodHints(QtCore.Qt.InputMethodHint.ImhSensitiveData)
        # set echo mode to password
        self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.EchoMode.Password)
        self.lineEdit_2.setClearButtonEnabled(True)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.db = Database()

        self.retranslateUi(Dialog)
        # if buttonbox accepted is clicked, launch login test
        self.login_button.clicked.connect(self.login)
        self.lresult = -1
        self.lusername = ""
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        Dialog.setWindowTitle("Login")

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "Username"))
        self.label_2.setText(_translate("Dialog", "Password"))

    def login(self):
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()
        # print(type(username), password)
        # Assuming 'Database' is a class to interact with your database

        hashed_password = hashlib.sha256(password.encode()).hexdigest()
        if len(self.db.getUsers()) == 0:
            AdminCommands().create_admin()
            self.lresult = 1  # Indicate successful login
            self.lusername = username
            self.dialog.accept()
        if self.db.login(username, hashed_password):
            self.lresult = 1  # Indicate successful login
            self.lusername = username
            logger.success(f"User {username} logged in.")
            self.dialog.accept()

        else:
            # Credentials are invalid, display a warning
            if username == "" or password == "":
                logger.warning("Invalid username or password. Login failed.")
                warning_dialog = QtWidgets.QMessageBox()
                warning_dialog.setIcon(QtWidgets.QMessageBox.Icon.Warning)
                warning_dialog.setText("Please enter a username and password.")
                warning_dialog.setWindowTitle("Login Failed")
                warning_dialog.exec()
            else:
                logger.warning("Invalid username or password. Login failed.")
                warning_dialog = QtWidgets.QMessageBox()
                warning_dialog.setIcon(QtWidgets.QMessageBox.Icon.Warning)
                warning_dialog.setText(
                    "Invalid username or password. Please try again."
                )
                warning_dialog.setWindowTitle("Login Failed")
                warning_dialog.exec()

    def cancel_buttonfn(self):
        self.dialog.reject()
