import platform
import subprocess
import sys
import time

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

# 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())
        self.archive_synch= ArchiveSynchronizer()

        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)
        self.ICON_EDIT = QIcon('src/ui/icons/edit.png')
        self.psw_edit_b.setIcon(self.ICON_EDIT)
        self.psw_edit_b.clicked.connect(self.show_osk)
        # TESTING
        if "--auto-login-admin" in sys.argv:
            self.user_cb.setCurrentText("ADMIN")
            self.password_le.setText("78900987")
        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()

    def show_osk(self):
        self.password_le.setFocus()
        # Use the virtual keyboard instead of the external one
        show_virtual_keyboard(self.password_le)
