#coding:utf-8
import commands

from PyQt4.QtCore import Qt, SIGNAL, QRect, QPoint
from PyQt4.QtGui import QVBoxLayout, QLabel, QLinearGradient, QKeySequence,QAction,QBrush,QColor,QPainter, QLineEdit, QPushButton, QPen, QHBoxLayout, \
    QDialog

from common.infohintdialog import InfoHintDialog
from controller.setting.chanpw import ChanPw


class PasswordDialog(QDialog):
    def __init__(self, parent = None):
        super(PasswordDialog,self).__init__(parent)
        self.setWindowTitle(u'密码验证')
        self.setStyleSheet("QWidget{font-size:10pt;}"
                           "QLineEdit{border:1px groove rgb(170,214,252);}"
                           "QLineEdit{height:25;}"
                           "QComboBox{border: 1px groove rgb(170,214,252);}"
                           "QComboBox{height:25;}"
                           "QComboBox::drop-down{border-bottom-right-radius: 3px;}"
                           "QComboBox::drop-down{subcontrol-origin: padding;}"
                           "QComboBox::drop-down{subcontrol-position: top right;}"
                           "QComboBox::drop-down{width: 20px;}"
                           "QComboBox::drop-down{border-left-width: 1px;}"
                           "QComboBox::drop-down{border-left-color: rgb(170,214,252);}"
                           "QComboBox::drop-down{border-left-style: solid;}"
                           "QComboBox::drop-down{border-top-right-radius: 3px;}"
                           "QComboBox::down-arrow {image:url(images/s2_r8_c10.gif);}"
                           "QPushButton{background:url(../images/button.png);border:2px;}"
                           )
        self.title = u'验证'
        self.setWindowFlags(Qt.Dialog|Qt.FramelessWindowHint)
#         self.setWindowModality(Qt.ApplicationModal)
        self.hintInfo = ""
        self.setFixedSize(350,200)
#         self.chanPw = ChanPw()
        self.tipLabel = QLabel(u"注意：仅管理员可以对终端进行设置，请先进行验证")
        self.tipLabel.setStyleSheet("QLabel{font-size:10pt;}")
        self.passwordLabel = QLabel(u"管理员密码:")
        self.passwordLineEdit = QLineEdit()
        self.passwordLineEdit.setEchoMode(QLineEdit.Password)
        #self.passwordLineEdit.setFocus(True)
        self.ensureBtn = QPushButton(u'登录')
        self.ensureBtn.setFixedSize(75,27)
        self.ensureBtn.setFlat(True)
        #self.ensureBtn.setFixedWidth(80)
        self.cancelBtn = QPushButton(u'取消')
        self.cancelBtn.setFixedSize(75,27)
        self.cancelBtn.setFlat(True)
        self.changePwButton = QPushButton(u"修改密码")
        self.changePwButton.setFixedSize(75,27)
        self.changePwButton.setFlat(True)
        self.changePwButton.setToolTip(u"点击可以修改管理员密码")
        
        topHLayout = QHBoxLayout()
        topHLayout.addSpacing(4)
        topHLayout.addWidget(self.tipLabel)
        #topHLayout.addSpacing(10)
        
        centreLayout = QHBoxLayout()
        centreLayout.addSpacing(10)
        centreLayout.addWidget(self.passwordLabel)
        centreLayout.addWidget(self.passwordLineEdit)
        centreLayout.addWidget(self.ensureBtn)
        centreLayout.addSpacing(10)
        
        bottomHLayout = QHBoxLayout()
        
        bottomHLayout.addWidget(self.changePwButton)
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.cancelBtn)
        
        mainVLayout = QVBoxLayout()
        #mainVLayout.setMargin(40)
        mainVLayout.addSpacing(50)
        mainVLayout.addLayout(topHLayout)
        mainVLayout.addSpacing(20)
        mainVLayout.addLayout(centreLayout)
        mainVLayout.addStretch()
        mainVLayout.addLayout(bottomHLayout)
        self.setLayout(mainVLayout)
        
        #self.okBtn.hide()
        
        self.connect(self.ensureBtn, SIGNAL("clicked()"),self.slotCheckPassWord)
        self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel)
        #self.connect(self.okBtn, SIGNAL("clicked()"),self.slotOk)
        self.connect(self.changePwButton,SIGNAL("clicked()"),self.changePw)
        
        self.mousePressed = False
        
        self.actionA = QAction(self)
        self.actionB = QAction(self)
        self.actionA.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_W))
        self.actionB.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_C))
        self.addAction(self.actionA)
        self.addAction(self.actionB)
        self.connect(self.actionA,SIGNAL("triggered()"),self.changePw)
        self.connect(self.actionB,SIGNAL("triggered()"),self.slotCancel)
        
    # 添加鼠标移动窗口
    def mouseMoveEvent(self,event):
        if self.mousePressed:
            self.move(self.pos() + event.pos() - self.currentPos)
   
    def mousePressEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.currentPos = event.pos()
            self.mousePressed = True
   
    def mouseReleaseEvent(self,event):
        if event.buttons() == Qt.LeftButton:
            self.mousePressed = False
    def changePw(self):
        chanPw = ChanPw()
        chanPw.exec_()
         
    def keyPressEvent(self,event):
        #keyEvent = QKeyEvent(event)
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            self.slotCheckPassWord()

    def slotCancel(self):
        self.close()
        
    def slotOk(self):
        self.passwordLabel.show()
        self.passwordLineEdit.show()
        self.ensureBtn.show()
        self.cancelBtn.show()
        self.tipLabel.show()
        self.changePwButton.show()
        
        self.okBtn.hide()
        self.setHintInfo("")
        
    def showHintInfo(self, info):
        self.passwordLabel.hide()
        self.passwordLineEdit.hide()
        self.ensureBtn.hide()
        self.cancelBtn.hide()
        self.changePwButton.hide()
        self.tipLabel.hide()
        self.okBtn.show()
        #self.okBtn.setFocus(True)
        self.okBtn.move((self.width() - self.okBtn.width())/2, self.height() - self.okBtn.height() - 10)
        self.setHintInfo(info)
        
    def slotCheckPassWord(self):
        passwd = self.passwordLineEdit.text()
        if passwd.isNull() or passwd.isEmpty():
            InfoHintDialog(u'请先输入终端管理员密码').exec_()
            return
    
        #读取/etc/shadow文件，获取以ｒｏｏｔ开头的行
        crypasswd = self.getSystemAdministratorPassword()
        if not crypasswd:
            InfoHintDialog(u'shadow文件中未存储root密码，无法完成验证').exec_()
            return
    
        if not self.checkPasswd(passwd,crypasswd):
            InfoHintDialog(u'密码错误，请确认后重新输入').exec_()
            return
        
        self.accept()
        return
        
    def checkPasswd(self, passwd,crypasswd):
        temp = crypasswd.split("$");
        count = len(temp)
        if 4 != count:
            return False
        alg = temp[1]
        salt= temp[2]
    
        passwdchar = passwd.toLatin1().data()
        randomchar = "$"+alg+"$"+salt+"$"
    
        # usercry = crypt.crypt(passwdchar,randomchar)
        # crystr= QString(QLatin1String(usercry))
        #
        # #加密后的密文与系统存储的ｒｏｏｔ密码密文想比较
        # if crypasswd == crystr:
        #     return True
        # return False
        
    def getSystemAdministratorPassword(self):
        #执行命令，收集结果
        output = None
        statusOutput = []
        statusOutput = commands.getstatusoutput("cat /etc/shadow | grep root:")
        if statusOutput[0] == 0:
            output = statusOutput[1]
        if not output:
            InfoHintDialog(u'读取系统密码异常').exec_()
            return None
        crylist = output.split(":")
        if len(crylist) < 2:
            InfoHintDialog(u'读取系统密码异常').exec_()
            return None
        return crylist[1]
    def paintEvent(self,event):
        titleHeight = 30
        bottomHeight = 2
        
        #画标题背景
        painter = QPainter(self)
        painter.save()
        linearGradient = QLinearGradient(0, 0,0,titleHeight)
        linearGradient.setColorAt(0, QColor(60,150,255))
        linearGradient.setColorAt(0.1, QColor(6,88,200))
        linearGradient.setColorAt(1, QColor(80,150,255))
        painter.setBrush(QBrush(linearGradient))
        contenRect = QRect(0, 0, self.width(), titleHeight)
        painter.fillRect(contenRect, QBrush(linearGradient))
        painter.restore()
        
        #画标题内容
        painter.save()
        painter.setPen(QPen(QColor(255, 255, 255),1))
        font = painter.font()
        font.setPointSize(12)
        painter.setFont(font)
        painter.drawText(QPoint(10,20), self.title)
        painter.restore()
        
        #画中间白色背景
        painter.save()
        painter.setPen(QPen(QColor(255, 255, 255),1))
        brush = QBrush(QColor(242,242,242))
        painter.setBrush(brush)
        contenRect = QRect(0, titleHeight, self.width()-1, self.height() - titleHeight - bottomHeight)
#         painter.fillRect(contenRect, brush)
        painter.drawRect(contenRect)
        painter.restore()
        
        #画底层背景
        painter.save()
        brush = QBrush(QColor(219,234,255))
        painter.setBrush(brush)
        contenRect = QRect(0, self.height() - bottomHeight, self.width(), bottomHeight)
        painter.fillRect(contenRect, brush)
        painter.restore()
        
        
        
