#coding:utf-8

from PyQt4.QtCore import Qt, SIGNAL
from PyQt4.QtGui import QLabel, QGridLayout, QHBoxLayout, QVBoxLayout, QPushButton, QPalette, QApplication, \
                        QLineEdit
from common.basedialog import BaseDialog
from common.infohintdialog import InfoHintDialog
from model.infomodel.userinfo import UserBaseInfo,  LoginUserInfo
from model.request.utilityrequestoperationwrap import UtilityRequestOperationWrap
import re, threading, json
from model.cfg.storeinfoparser import StoreInfoParser

class PasswordEditDialog(BaseDialog):
        
    def __init__(self, passwordType="Force", parent = None):
        super(PasswordEditDialog,self).__init__(parent)
        self.setWidgetSysAttr()
        
        self.passwordType = passwordType
        self.pattern = "^(?![a-zA-Z0-9]+$)(?![^a-zA-Z/D]+$)(?![^0-9/D]+$).{8,40}$" if passwordType == "Force" \
                        else "^.{6,}$"
        
        self.initSubWidget()
        
        self.initLayout()
        
        self.bandSignalSlot()
        
        
    def initSubWidget(self):
        
        self.oldPasswordLabel = QLabel(u"原密码")
        self.oldPasswordLineEdit = QLineEdit()
        self.oldPasswordLineEdit.setEchoMode(QLineEdit.Password)
        
        self.newPasswordLabel = QLabel(u"新密码")
        self.newPasswordLineEdit = QLineEdit()
        self.newPasswordLineEdit.setEchoMode(QLineEdit.Password)
        
        self.confirmPasswordLabel = QLabel(u"确认密码")
        self.confirmPasswordLineEdit = QLineEdit()
        self.confirmPasswordLineEdit.setEchoMode(QLineEdit.Password)
        
        self.infoHineLabel = QLabel()
        
        pa = QPalette()
        pa.setColor(QPalette.WindowText,Qt.red)
        self.infoHineLabel.setPalette(pa)
        
        self.saveBtn = QPushButton(u'保存')
        self.saveBtn.setObjectName('saveButton')
        self.saveBtn.setFixedSize(75,30)
        
        self.cancelBtn = QPushButton(u'取消')
        self.cancelBtn.setObjectName('cancelButton')
        self.cancelBtn.setFixedSize(75,30)
        
        
    def initLayout(self):
        gridLayout = QGridLayout()
        gridLayout.setSpacing(15)
        gridLayout.setContentsMargins(0, 0, 0, 0)
        
        gridLayout.addWidget(self.oldPasswordLabel, 0, 0)
        gridLayout.addWidget(self.oldPasswordLineEdit, 0, 1)
        
        gridLayout.addWidget(self.newPasswordLabel, 1, 0)
        gridLayout.addWidget(self.newPasswordLineEdit, 1, 1)
        gridLayout.addWidget(self.confirmPasswordLabel, 2, 0)
        gridLayout.addWidget(self.confirmPasswordLineEdit, 2, 1)
        
        hGridLayout = QHBoxLayout()
        hGridLayout.setSpacing(0)
        hGridLayout.setContentsMargins(0, 0, 0, 0)
        hGridLayout.addSpacing(60)
        hGridLayout.addLayout(gridLayout)
        hGridLayout.addSpacing(60)
        
        hTLayout = QHBoxLayout()
        hTLayout.setSpacing(0)
        hTLayout.setContentsMargins(0, 0, 0, 0)
        hTLayout.addStretch()
        hTLayout.addWidget(self.infoHineLabel)
        hTLayout.addStretch()
        
        hBLayout = QHBoxLayout()
        hBLayout.setSpacing(0)
        hBLayout.setContentsMargins(0, 0, 0, 0)
        hBLayout.addStretch()
        hBLayout.addWidget(self.saveBtn)
        hBLayout.addSpacing(10)
        hBLayout.addWidget(self.cancelBtn)
        hBLayout.addStretch()
        
        mainVLayout = QVBoxLayout()
        mainVLayout.setSpacing(0)
        mainVLayout.setContentsMargins(0, 0, 0, 0)
        mainVLayout.addSpacing(60)
        mainVLayout.addLayout(hGridLayout)
        mainVLayout.addLayout(hTLayout)
        mainVLayout.addLayout(hBLayout)
        mainVLayout.addSpacing(5)
        self.setLayout(mainVLayout)
        
    def bandSignalSlot(self):
        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)
        self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel)
        self.connect(self, SIGNAL("changePasswordFailed"),self.slotPopFailedHintInfo)
        self.connect(self, SIGNAL("changePasswordSuccess"),self.slotPopSuccessHintInfo)
        
    def slotPopFailedHintInfo(self, info):
        print "info:", info
        if info == "ConnectionError":
            InfoHintDialog(u'修改密码失败，请查看网络连接是否正常！').exec_()
        elif info == "forbidden":
            InfoHintDialog(u'该用户没有管理员权限，不能修改用户密码！').exec_()
        else:
            InfoHintDialog(u'修改密码失败！').exec_()
        
    def slotPopSuccessHintInfo(self):
        self.accept()
        InfoHintDialog(u'修改密码成功！').exec_()
        
        
    def setWidgetSysAttr(self):
        self.setTitle(u"修改密码")
        self.setFixedSize(500, 250)
        
    def slotCancel(self):
        self.reject()
        
    def slotSave(self):
        oldPw = self.oldPasswordLineEdit.text()
        newPassword = self.newPasswordLineEdit.text()
        newConfirmPassword = self.confirmPasswordLineEdit.text()
        
        if not oldPw:
            InfoHintDialog(u'原密码不得为空，请重新输入').exec_()
            return 
        
        if not newPassword:
            InfoHintDialog(u'新密码不得为空，请重新输入').exec_()
            return 
        
        if not newConfirmPassword:
            InfoHintDialog(u'确认密码不得为空，请重新输入').exec_()
            return 
        
        loginUserInfo = LoginUserInfo.instance().getUserInfo()
        if loginUserInfo.password != oldPw:
            InfoHintDialog(u'原密码输入有误，请重新输入').exec_()
            return 
        
        
        if newPassword != newConfirmPassword:
            InfoHintDialog(u'新密码和确认密码不相同，请重新输入').exec_()
            self.newPasswordLineEdit.setFocus()
            return
        
        def changPassword(userName, newPassword):    
            utility = UtilityRequestOperationWrap()
            resultValue = utility.changeUserPassword(userName, newPassword)
            if resultValue == "ConnectionError" or resultValue == "forbidden" or resultValue is None: 
                self.emit(SIGNAL("changePasswordFailed"), resultValue)
                return
            
            if resultValue is True:
                self.emit(SIGNAL("changePasswordSuccess"))
                loginUserInfo.password = newPassword
                
                autoLoginInfo = StoreInfoParser.instance().getAutoLoginInfo()
                if autoLoginInfo is not None:
                    autoLoginInfoDict = json.loads(autoLoginInfo)
                    if autoLoginInfoDict["userName"] == loginUserInfo.name and \
                                            autoLoginInfoDict["serverIp"] == loginUserInfo.serverIp:
                        newAutoLoginInfo = { "userName": loginUserInfo.name,
                              "password": newPassword,
                              "serverIp": loginUserInfo.serverIp,
                              "centerName": str(autoLoginInfoDict["centerName"]),
                                    }
                        
                        StoreInfoParser.instance().setAutoLoginInfo(json.dumps(newAutoLoginInfo, ensure_ascii=False))
                        
        
        tContext = threading.Thread(target=changPassword, args=(loginUserInfo.name, str(newPassword), ))
        tContext.start()
        

        
# import sys
#  
# app = QApplication(sys.argv)
# print "start"
# c = PasswordEditDialog("Common")
# c.show()
# app.exec_()

        
            
        