#!/usr/bin/env python

from qt import *
from loginBA import LoginBA
from workerThread import WorkerThread
import logging
from constants import EVENT_LOGIN
from messageQueue import mainMessageQueue
from loginSettings import LoginSettings
import os
from help import Help
try:
    from base64 import b32encode, b32decode
except ImportError:
    from python24.base64 import b32encode, b32decode


debug = logging.getLogger("login").debug
error = logging.getLogger("login").error

class Login(LoginBA):
    def __init__(self, parent, data_path, login_func, autologin, *args):
        """
        Initialize the login dialog
        
        parent: parent window
        data_path: path of releaseforge data directory
        login_func: function to invoke on login success
        autologin: attempt to automatically login (w/o displaying this dialog)
        """
        
        apply(LoginBA.__init__,(self,) + args)
        self.parent = parent
        self.data_path = data_path
        self.autologin = autologin
        
        self.setCaption(self.server_name_ + " Login")
        self.groupBox.setTitle(self.server_name_ + " Login")
        
        self.settings = LoginSettings(data_path)
        username = self.settings[self.username_]
        password = self.settings[self.password_]
        try:
            if password: password = b32decode(password)
        except:
            QMessageBox.warning(self, "Password Reset",
                                "Could not decode your saved password."
                                "You will need to re-enter it.")
            password = ""
        
        
        self.usernameLineEdit.setText(username)
        self.passwordLineEdit.setText(password)
        rememberMe = self.settings[self.remember_password_]
        if rememberMe.lower() in ('1', 'true'):
            self.rememberCheckBox.setChecked(True)
        self.login_func = login_func
        self.thread = None

        try_autologin = False
        if username and password:
            self.buttonOk.setFocus()
            if self.autologin:
                try_autologin = True
        elif username: self.passwordLineEdit.setFocus()
        
        if try_autologin:
            self.username = username
            self.password = password
            self.remember = True
            self.login()
        else:
            self.show()



    def customEvent(self, event):
        if event.type() != EVENT_LOGIN: return
        
        response = event.data()
        debug("customEvent: %s", response)
        self.setCursor(Qt.arrowCursor)
        self.parent.setCursor(Qt.arrowCursor)
        self.parent.statusBar().clear()
        self.setEnabled(True)
        #self.parent.setCursor(Qt.arrowCursor)
        if not response:
            if self.autologin: self.show()
            QMessageBox.critical(self, "Login Failed",
                                 "Unable to login to %s.\n" 
                                 "Please verify your username and password." % self.server_name_)
            self.enableElements()
            return

        settings = self.settings
        settings[self.username_] = self.username
        settings[self.remember_password_] = self.remember
        if self.remember:
            settings[self.password_] = b32encode(self.password)
        else:
            settings[self.password_] = ""

        settings.saveSettings()
            
        self.parent.emit(PYSIGNAL(self.signal_), (response,) )
        LoginBA.accept(self)


    def __del__(self):
        if self.thread:
            t = self.thread
            running = t.running()
            t.stop()
            if not t.finished():
                t.wait()

    def help(self):
        self._help = Help(self, "login.html")
        

    def disableElements(self):
        self.enableElements(False)


    def enableElements(self, enable=True):
        self.usernameLineEdit.setEnabled(enable)
        self.passwordLineEdit.setEnabled(enable)
        self.rememberCheckBox.setEnabled(enable)
        self.buttonOk.setEnabled(enable)

        
    def reject(self):
        if self.thread: self.thread.stop()
        mainMessageQueue.put("%s login cancelled" % self.server_name_)
        LoginBA.reject(self)
        
        
    def accept(self):
        self.username = str(self.usernameLineEdit.text())
        self.password = str(self.passwordLineEdit.text())
        self.remember = bool(self.rememberCheckBox.isChecked()) # True/False

        if not self.username or not self.password:
            QMessageBox.critical(self, "Login Failed",
                                 "You must supply a valid username and password.\n")
            return

        self.disableElements()

        self.login()


    def login(self):
        self.setCursor(Qt.waitCursor)
        self.parent.setCursor(Qt.waitCursor)
        mainMessageQueue.put("Authenticating user")

        self.thread = WorkerThread(self,
                                   EVENT_LOGIN,
                                   self.login_func,
                                   self.username,
                                   self.password)
        self.thread.start()

