import sys

from lib.db import Session, Users
from PyQt5.QtCore import QTimer, pyqtSignal
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QMessageBox, QShortcut
from ui.widget import Widget

# TESTING
login_count = 0
# /TESTING


class Login(Widget):
    wrong_credentials = pyqtSignal()
    successful_login = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.welcome_l.setText("BENVENUTO, PER INIZIARE IL COLLAUDO, EFFETTUA L'ACCESSO:")
        self.user_cb.addItems(Users.get_usernames())
        QShortcut(QKeySequence("Return"), self).activated.connect(self.login_b.click)
        QShortcut(QKeySequence("Enter"), self).activated.connect(self.login_b.click)
        self.login_b.clicked.connect(self.try_login)
        # TESTING
        if "--auto-login-admin" in sys.argv:
            self.user_cb.setCurrentText("ADMIN")
            self.password_le.setText("123123")
        elif "--auto-login-user" in sys.argv or "--test" in sys.argv:
            self.user_cb.setCurrentText("USER")
            self.password_le.setText("user")
        if "--auto-login-admin" in sys.argv or "--auto-login-user" in sys.argv or "--test" in sys.argv:
            global login_count
            if login_count <= 0:
                self.test_timer = QTimer()
                self.test_timer.setSingleShot(True)
                self.test_timer.timeout.connect(self.login_b.clicked.emit)
                self.test_timer.start(500)
        # /TESTING

    def try_login(self):
        user = self.user_cb.currentText().upper()
        password = self.password_le.text()
        session = Users.login(user, password)
        if type(session) is not Session:
            self.wrong_credentials.emit()
            QMessageBox.critical(None, "Errore login", "Credenziali errate")
        else:
            # TESTING
            global login_count
            login_count += 1
            # /TESTING
            self.successful_login.emit()
