#coding=utf-8
from PyQt4.QtGui import QDialog, QLineEdit, QKeyEvent
from PyQt4.QtCore import Qt, QString, SIGNAL
from view.desktop.loginview import Ui_Form
from common.globalfun import moveWidgetToScreenCenter
from common.infohintdialog import InfoHintDialog
from model.infomodel.userinfo import UserBaseInfo,  LoginUserInfo
import threading
from model.request.utilityrequestoperationwrap import UtilityRequestOperationWrap
from controller.setting.setting import Setting
from common import globalfun
from model.cfg.storeinfoparser import StoreInfoParser
from controller.setting.passworddialog import PasswordDialog
from controller.terminaltool.terminalset import TerminalTools
from controller.help.helpdialog import HelpDialog
import json
 
class LoginDlg(QDialog, Ui_Form):
    def __init__(self, parent=None):
        super(LoginDlg,self).__init__(parent)
        
        #--------------界面初始化-top
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setStyleSheet(QString("QWidget#Form{background-image: url(../images/login.png);}"))
        self.lineEditPassword.setEchoMode(QLineEdit.Password)
        self.pushButtonLogin.setObjectName("loginBtn")
        self.pushButtonLogin.setFlat(True)
        #--------------界面初始化-end
        
        self.initSubWidgetInfo()
        self.bandSignalSlot()
        self.setMouseTracking(True)
        
    def initSubWidgetInfo(self):
        self.initCenterList()
        self.initVersionInfo()
        self.initAutoLoginUserInfo()
        
        #登录框移动到屏幕中心
        moveWidgetToScreenCenter(self, checkMulMonitor=False)
        
    def initVersionInfo(self):
        version = globalfun.getVersionAndReleaseDate()
        if version:
            self.labelVerName.setText(u"%s" % version)
            
    def setAutoLoginUserInfo(self):
        autoLoginInfo = StoreInfoParser.instance().getAutoLoginInfo()
        if autoLoginInfo is not None:
            self.checkBoxRemberUsername.setChecked(True)
            self.checkBoxAutoLogin.setChecked(True)
            autoLoginInfoDict = json.loads(autoLoginInfo)
            self.lineEditUserName.setText(autoLoginInfoDict["userName"])
            self.lineEditPassword.setText(autoLoginInfoDict["password"])
            centerName = autoLoginInfoDict["centerName"]
            num = self.comboBoxCenter.count()
            for i in range(num):
                subCenterName = self.getCenterComboxText(i)
                if subCenterName == centerName:
                    self.comboBoxCenter.setCurrentIndex(i)
                    break
                
        return
            
    def checkHasAutoLoginUser(self):
        return True if StoreInfoParser.instance().getAutoLoginInfo() is not None else False
    
    
    def checkRememberUserName(self):
        return True if StoreInfoParser.instance().getLoginUserName() is not None else False
    
    
    def setRemeberUserName(self):
        loginUserInfo = StoreInfoParser.instance().getLoginUserName()
        if loginUserInfo is not None:
            self.lineEditUserName.setText(loginUserInfo)
            self.checkBoxRemberUsername.setChecked(True)
    
    
    def initAutoLoginUserInfo(self):
        if self.checkHasAutoLoginUser():
            self.setAutoLoginUserInfo()
            return
        
        if self.checkRememberUserName():
            self.setRemeberUserName()
            
        return
        
        
    def initCenterList(self):
        self.comboBoxCenter.clear()
        centerContent = StoreInfoParser.instance().getCenterList()
        if centerContent is None:
            return
         
        preCenterName = StoreInfoParser.instance().getLoginCenterName()
        preIndex = -1
        contentDict = json.loads(centerContent)
        for index, center in enumerate(contentDict.keys()):
            self.comboBoxCenter.addItem(center)
            self.comboBoxCenter.setItemData(index, contentDict[center]["centerIp"], Qt.UserRole)
            self.comboBoxCenter.setItemData(index, contentDict[center]["networkName"], Qt.UserRole + 1)
            if center == preCenterName:
                preIndex = index
                
        if preIndex != -1:
            self.comboBoxCenter.setCurrentIndex(preIndex)
            
    def updateCenterList(self):
        self.comboBoxCenter.clear()
        centerContent = StoreInfoParser.instance().getCenterList()
        if centerContent is None:
            return
         
        contentDict = json.loads(centerContent)
        for index, center in enumerate(contentDict.keys()):
            self.comboBoxCenter.addItem(center)
            self.comboBoxCenter.setItemData(index, contentDict[center]["centerIp"], Qt.UserRole)
            self.comboBoxCenter.setItemData(index, contentDict[center]["networkName"], Qt.UserRole + 1)
            
        
    def bandSignalSlot(self):
        self.connect(self.pushButtonLogin, SIGNAL("clicked()"),self.slotLogin)
        self.connect(self.pushButtonLoginSet, SIGNAL("clicked()"),self.slotPopSettingDlg)
        self.connect(self.pushButtonTermai, SIGNAL("clicked()"),self.slotPopTerminalToolDlg)
        self.connect(self.pushButtonHelp, SIGNAL("clicked()"),self.slotPopHelpDlg)
        self.connect(self, SIGNAL("authFailed"),self.slotLoginFailed)
        self.connect(self, SIGNAL("authSuccess"),self.changeLoginBack)
        
        
    def slotLoginFailed(self, checkValue):
        self.changeLoginBack()
        
        if checkValue is None:
            InfoHintDialog(u"登录失败，请查看用户名和密码是否正确！").exec_()
        elif checkValue == "ConnectionError":
            InfoHintDialog(u"登录失败，请查看网络连接是否正常！").exec_()
        
    def slotPopTerminalToolDlg(self):
        toolDlg = TerminalTools()
        toolDlg.exec_()
        
    def slotPopHelpDlg(self):
        helpDlg = HelpDialog()
        moveWidgetToScreenCenter(helpDlg)
        helpDlg.exec_()
        
    def slotPopSettingDlg(self):
        passwordDialog = PasswordDialog()
        if passwordDialog.exec_() == QDialog.Accepted:
            setWidget = Setting()
            self.connect(setWidget, SIGNAL("updateCenterDateS"), self.updateCenterList)
            self.connect(setWidget, SIGNAL("setscreenover"), self.adjustPosition)
            setWidget.exec_()
            
            
    def adjustPosition(self):
        self.emit(SIGNAL("moveWidgetToScreenCenter"))
        
        
    def checkIsRecordLoginUserInfo(self):
        if self.checkBoxRemberUsername.isChecked():
            StoreInfoParser.instance().setLoginUserName(self.getLoginUserName())
        else:
            StoreInfoParser.instance().deleteLoginUserName()
                
        StoreInfoParser.instance().setLoginCenterName(self.getLoginCenterName())
                
        if self.checkBoxAutoLogin.isChecked():
            autoLoginInfo = { "userName": self.getLoginUserName(),
                              "password": self.getPassword(),
                              "serverIp": self.getLoginCenterIP(),
                              "centerName": self.getLoginCenterName(),
                                    }
            
            StoreInfoParser.instance().setAutoLoginInfo(json.dumps(autoLoginInfo, ensure_ascii=False))
        else:
            StoreInfoParser.instance().deleteAutoLoginInfo()
            
            
    def slotLogin(self):
        if not self.checkLoginInfo():
            return
        
        self.setLoginUserInfo()
        self.changeLoginDisplay()

        def authHttpRequest():          
            utility = UtilityRequestOperationWrap()
            vmBaseInfoList = utility.checkloginAuth()
            if vmBaseInfoList == None or vmBaseInfoList == "ConnectionError":
                self.emit(SIGNAL("authFailed"), vmBaseInfoList) 
                return
            
            self.checkIsRecordLoginUserInfo()
                
            self.emit(SIGNAL("authSuccess"), vmBaseInfoList)
        
        tContext = threading.Thread(target=authHttpRequest)
        tContext.start()
        
        
    def setLoginUserInfo(self):
        userBaseInfo = UserBaseInfo()
        userBaseInfo.name, userBaseInfo.password, userBaseInfo.serverIp = self.getLoginInfo()
        LoginUserInfo.instance().setUserInfo(userBaseInfo)
    
    def resetWidgetInfo(self):
        if not self.checkBoxRemberUsername.isChecked():
            self.lineEditUserName.clear()
        self.lineEditPassword.clear()
    
    def checkLoginInfo(self):
        userName, password, centerIP = self.getLoginInfo()
        
        if not userName or not password:
            InfoHintDialog(u"用户名或密码不能为空！").exec_()
            return False
        
        if not centerIP:
            InfoHintDialog(u"请选择相应的中心！").exec_()
            return False
        
        return True
    
    def getLoginInfo(self):
        userName = self.getLoginUserName()
        password = self.getPassword()
        centerIP = self.getLoginCenterIP()
        return userName, password, centerIP
    
    def getLoginUserName(self):
        return unicode(str(self.lineEditUserName.text().trimmed()), "utf-8")
    
    def getLoginCenterIP(self):
        index = self.comboBoxCenter.currentIndex()
        return str(self.comboBoxCenter.itemData(index, Qt.UserRole).toString()) 
    
    def getLoginCenterName(self):
        return unicode(str(self.comboBoxCenter.currentText().trimmed()), "utf-8")
    
    def getCenterComboxText(self, index):
        return unicode(str(self.comboBoxCenter.itemText(index).trimmed()), "utf-8")
    
    def getPassword(self):
        return str(self.lineEditPassword.text())
    
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            self.slotLogin()
        
    def changeLoginDisplay(self):
        self.pushButtonLogin.setEnabled(False)
        self.pushButtonLogin.setText(u"登录中...")
        
   
    def changeLoginBack(self):
        self.pushButtonLogin.setEnabled(True)
        self.pushButtonLogin.setText(u"登  录")
 
 