#coding:utf-8
from PyQt4 import QtCore
from PyQt4 import QtGui
import os
import subprocess
from PyQt4.QtCore import Qt

from LockScreen import LockScreen
from logger.logrecord import LogRecord
from WaitingDialog import WaitingDialog


class PowerOffDialog(QtGui.QDialog):
    """
    关机重启对话框
    """
    def __init__(self,parent=None,login=None):
        QtGui.QDialog.__init__(self,parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setModal(True)
        self.isReStart=True

        self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.X11BypassWindowManagerHint)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground,False)
        self.setStyleSheet("QDialog{background-color:rgba(230,230,230,255);}")

        self.__imagePath=os.getenv('WIN_UI_IMAGES_PATH')

        self.__waiting=WaitingDialog()
        self.showRDPSignal=QtCore.pyqtSignal()
        self.logout_timer=QtCore.QTimer()
        self.__timeout=10000

        self.refresh()
        self.connect(self.contentLabel.restartBtn,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onRestart()'))
        self.connect(self.contentLabel.powerOffBtn,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onPowerOff()'))
        self.connect(self.contentLabel.lockScreenBtn,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onLockScreen()'))
        self.connect(self.topLabel.closePushButton,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onCloseBtn()'))
        self.connect(self.bottomLabel.canncelBtn,QtCore.SIGNAL('clicked()'),self,QtCore.SLOT('onCloseBtn()'))
        self.connect(self,QtCore.SIGNAL('showRDPSignal'),login,QtCore.SIGNAL('showRDPSignal'))
        self.connect(self.logout_timer,QtCore.SIGNAL("timeout()"),self,QtCore.SLOT("logoutTimeout()"))


    def refresh(self):
        """
        用来刷新对话框界面位置，应对修改分辨率
        :return:
        """
        from common import common_run


        topFont=QtGui.QFont()
        topFont.setPointSize(common_run.get_height(16))
        self.topLabel=QtGui.QLabel(self)
        self.topLabel.leftLabel=QtGui.QLabel(self.topLabel)
        self.topLabel.middleLabel=QtGui.QLabel(self.topLabel)
        self.topLabel.rightLabel=QtGui.QLabel(self.topLabel)
        self.topLabel.nameLabel=QtGui.QLabel(self.topLabel)

        self.topLabel.nameLabel.setText("   关机".decode('utf-8'))
        self.topLabel.nameLabel.setFont(topFont)

        self.topLabel.closePushButton=QtGui.QPushButton(self.topLabel)
        self.topLabel.closePushButton.setFlat(True)
        self.topLabel.closePushButton.setFocusPolicy(QtCore.Qt.NoFocus)

        self.contentLabel=QtGui.QLabel(self)
        self.contentLabel.restartBtn=QtGui.QPushButton(self.contentLabel)
        # self.contentLabel.restartBtn.setText('重启'.decode('utf-8'))
        self.contentLabel.restartBtn.setFlat(True)
        self.contentLabel.restartBtn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.contentLabel.restartLabel=QtGui.QLabel(self.contentLabel)
        self.contentLabel.restartLabel.setText('重启'.decode('utf-8'))
        self.contentLabel.restartLabel.setAlignment(QtCore.Qt.AlignCenter)


        self.contentLabel.powerOffBtn=QtGui.QPushButton(self.contentLabel)
        # self.contentLabel.powerOffBtn.setText('关机'.decode('utf-8'))
        self.contentLabel.powerOffBtn.setFlat(True)
        self.contentLabel.powerOffBtn.setFocusPolicy(QtCore.Qt.NoFocus)

        self.contentLabel.powerOffLabel=QtGui.QLabel(self.contentLabel)
        self.contentLabel.powerOffLabel.setText('关机'.decode('utf-8'))
        self.contentLabel.powerOffLabel.setAlignment(QtCore.Qt.AlignCenter)

        self.contentLabel.lockScreenBtn=QtGui.QPushButton(self.contentLabel)
        # self.contentLabel.lockScreenBtn.setText('锁屏'.decode('utf-8'))
        self.contentLabel.lockScreenBtn.setFlat(True)
        self.contentLabel.lockScreenBtn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.contentLabel.lockScreenLabel=QtGui.QLabel(self.contentLabel)
        self.contentLabel.lockScreenLabel.setText('锁屏'.decode('utf-8'))
        self.contentLabel.lockScreenLabel.setAlignment(QtCore.Qt.AlignCenter)

        self.bottomLabel=QtGui.QLabel(self)
        self.bottomLabel.leftLabel=QtGui.QLabel(self.bottomLabel)
        self.bottomLabel.middleLabel=QtGui.QLabel(self.bottomLabel)
        self.bottomLabel.rightLabel=QtGui.QLabel(self.bottomLabel)
        self.bottomLabel.canncelBtn=QtGui.QPushButton(self.bottomLabel)
        self.bottomLabel.canncelBtn.setFlat(True)
        self.bottomLabel.canncelBtn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.update_geometry()


    def update_geometry(self):
        from common import common_run
        self.__width = 2 * common_run.getScreenWidth() / 5
        self.__height = self.__width / 2
        self.__topHeight=3*self.__height//20
        self.__bottomHeight=self.__height//5
        self.__buttonWidth=self.__height//4
        self.__buttonHeight=self.__buttonWidth
        self.__buttonSpace=(self.__width-3*self.__buttonWidth)//4
        self.setGeometry(0,0,self.__width,self.__height)
        self.setGeometry((common_run.getScreenWidth()-self.width())//2,(common_run.getScreenHeight()-self.height())//2,self.width(),self.height())
        self.setFixedSize(self.__width,self.__height)

        self.topLabel.setGeometry(0,0,self.__width,self.__topHeight)
        self.topLabel.setStyleSheet("QLabel{background:transparent;}")
        self.topLabel.leftLabel.setGeometry(0,0,self.__topHeight*16//15,self.__topHeight)
        self.topLabel.leftLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/left_top.png);background:transparent;}"%self.__imagePath)
        self.topLabel.rightLabel.setGeometry(self.__width-self.__topHeight*16//15,0,self.__topHeight*16//15,self.__topHeight)
        self.topLabel.rightLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/right_top.png);background:transparent;}"%self.__imagePath)
        self.topLabel.middleLabel.setGeometry(self.__topHeight*16//15,0,self.__width-2*self.__topHeight*16//15+1,self.__topHeight)
        self.topLabel.middleLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/middle_top.png);background:transparent;}"%self.__imagePath)
        self.topLabel.nameLabel.setStyleSheet("")
        self.topLabel.nameLabel.setGeometry(10,0,70,self.__topHeight)
        self.topLabel.closePushButton.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/close1.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/close2.png);background:transparent;}"%self.__imagePath)

        self.contentLabel.setGeometry(0,self.__topHeight,self.width(),self.height()-self.__topHeight-self.__bottomHeight)
        self.contentLabel.setStyleSheet("QLabel{background-color:rgb(255,255,255);}")
        self.contentLabel.restartBtn.setGeometry((self.__width-(3*self.__buttonWidth+2*self.__buttonSpace))//2,(self.contentLabel.height()-self.__buttonHeight*3//2)//2,self.__buttonWidth,self.__buttonHeight)
        self.contentLabel.restartLabel.setGeometry((self.__width-(3*self.__buttonWidth+2*self.__buttonSpace))//2,(self.contentLabel.height()//2+self.__buttonHeight//4),self.__buttonWidth,self.__buttonHeight//3)

        self.contentLabel.powerOffBtn.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/powerOff1.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/powerOff2.png);background:transparent;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/powerOff3.png);background:transparent;}"%self.__imagePath)

        self.contentLabel.lockScreenBtn.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/lockScreen1.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/lockScreen2.png);background:transparent;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/lockScreen3.png);background:transparent;}"%self.__imagePath)
        self.bottomLabel.canncelBtn.setGeometry(self.__width-self.__width//4-self.__bottomHeight,self.__bottomHeight//8,self.__width//4,3*self.__bottomHeight//4)
        self.bottomLabel.canncelBtn.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/cancel.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/cancel1.png);background:transparent;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/cancel2.png);background:transparent;}"%self.__imagePath)
        self.topLabel.closePushButton.setGeometry(self.topLabel.width()-self.__topHeight*16//15,0,self.__topHeight*16//15,self.__topHeight)
        self.contentLabel.restartBtn.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/restart1.png);background:transparent;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/restart2.png);background:transparent;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/restart3.png);background:transparent;}"%self.__imagePath)

        self.contentLabel.powerOffBtn.setGeometry((self.__width-(self.__buttonWidth))//2,(self.contentLabel.height()-self.__buttonHeight*3//2)//2,self.__buttonWidth,self.__buttonHeight)
        self.contentLabel.powerOffLabel.setGeometry((self.__width-(self.__buttonWidth))//2,(self.contentLabel.height()//2+self.__buttonHeight//4),self.__buttonWidth,self.__buttonHeight//3)
        self.contentLabel.lockScreenBtn.setGeometry((self.__width//2+(self.__buttonWidth//2+self.__buttonSpace)),(self.contentLabel.height()-self.__buttonHeight*3//2)//2,self.__buttonWidth,self.__buttonHeight)
        self.contentLabel.lockScreenLabel.setGeometry((self.__width//2+(self.__buttonWidth//2+self.__buttonSpace)),(self.contentLabel.height()//2+self.__buttonHeight//4),self.__buttonWidth,self.__buttonHeight//3)
        self.bottomLabel.setGeometry(0,self.height()-self.__bottomHeight,self.width(),self.__bottomHeight)
        self.bottomLabel.setStyleSheet("QLabel{background:transparent;}")
        self.bottomLabel.leftLabel.setGeometry(0,0,self.__bottomHeight*4//5,self.__bottomHeight)
        self.bottomLabel.leftLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/left_bottom.png);background:transparent;}"%self.__imagePath)
        self.bottomLabel.middleLabel.setGeometry(self.__bottomHeight*4//5,0,self.__width-2*self.__bottomHeight*4//5+1,self.__bottomHeight)
        self.bottomLabel.middleLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/middle_bottom.png);background:transparent;}"%self.__imagePath)
        self.bottomLabel.rightLabel.setGeometry(self.__width-self.__bottomHeight*4//5,0,self.__bottomHeight*4//5,self.__bottomHeight)
        self.bottomLabel.rightLabel.setStyleSheet("QLabel{border-image:url(%s/settingWindow/right_bottom.png);background:transparent;}"%self.__imagePath)

        contentFont=QtGui.QFont()
        contentFont.setPointSize(common_run.get_height(14.0))
        self.contentLabel.restartLabel.setFont(contentFont)
        self.contentLabel.powerOffLabel.setFont(contentFont)
        self.contentLabel.lockScreenLabel.setFont(contentFont)


        
    def mousePressEvent(self,event):
        if event.button() == QtCore.Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self,event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

    @QtCore.pyqtSlot()
    def onCloseBtn(self):
        self.emit(QtCore.SIGNAL("showRDPSignal"))
        LogRecord.instance().logger.debug('PowerOffDialog onCloseBtn')
        self.hide()

    @QtCore.pyqtSlot()
    def onRestart(self):
        """
        重启
        :return:
        """
        LogRecord.instance().logger.debug('重启')
        self.hide()
        self.isReStart=True
        self.logout_timer.start(self.__timeout)
        self.emit(QtCore.SIGNAL("LOGOUT"))
        self.__waiting.showMsg("正在注销用户...".decode('utf-8'))
        self.__waiting.showFullScreen()
        # os.system('sudo reboot')

    @QtCore.pyqtSlot()
    def onPowerOff(self):
        """
        关机
        :return:
        """
        LogRecord.instance().logger.debug('关机')
        self.hide()
        self.isReStart=False
        self.logout_timer.start(self.__timeout)
        self.emit(QtCore.SIGNAL("LOGOUT"))
        self.__waiting.showMsg("正在注销用户...".decode('utf-8'))
        self.__waiting.show()
        # os.system('sudo poweroff ')

    @QtCore.pyqtSlot()
    def logoutTimeout(self):
        """
        注销等待超时
        :return:
        """
        LogRecord.instance().logger.info("注销用户超时，继续关机或重启！")
        self.logout_over(False)

    def logout_over(self,result):
        """
        注销后，处理关机和重启事件
        :param result:注销是否成功
        :return:
        """
        self.logout_timer.stop()
        if result:
            self.__waiting.showMsg("注销用户成功！".decode('utf-8'))
        else:
            LogRecord.instance().logger.warn("注销用户失败，继续关机或重启！")
            self.__waiting.showMsg("注销用户失败！".decode('utf-8'))
        self.__waiting.close()
        if self.isReStart:
            os.system('sudo reboot')
        else:
            os.system('sudo poweroff ')

    @QtCore.pyqtSlot()
    def onLockScreen(self):
        """
        锁屏
        :return:
        """
        LogRecord.instance().logger.debug('锁屏')
        self.hide()
        self.lockScreen=LockScreen()
        self.connect(self.lockScreen,QtCore.SIGNAL('showRDPSignal'),self,QtCore.SIGNAL('showRDPSignal'))
        self.lockScreen.show()

class powerListen():
    """
    监听电源按键事件
    """
    def __init__(self,powerpressed):
        self.pressed=powerpressed

    def listen(self):
        try:
            acpi_listen=subprocess.Popen("acpi_listen", stdout=subprocess.PIPE)
            while True:
                try:
                    outStr=acpi_listen.stdout.readline()
                    # LogRecord.instance().logger.info("监控电源键返回消息："+outStr)
                    if outStr.find('button/power') >= 0:
                        print "button / power ... ......."
                        LogRecord.instance().logger.info("收到电源键按下事件！")
                        self.pressed()
                except Exception,err:
                    LogRecord.instance().logger.exception("读取命令‘acpi_listen’返回值，异常！")
                    break
        except Exception,err:
            LogRecord.instance().logger.exception("执行命令‘acpi_listen’，异常！")

# if __name__ == "__main__":
#     import sys
#     os.environ["WIN_UI_IMAGES_PATH"]="../../images"
#     app = QtGui.QApplication(sys.argv)
#     # import commands
#     # status,output = commands.getstatusoutput('acpi_listen')
#     # print status,output
#     # powerListen.listen()
#     powerOffDialog=PowerOffDialog();
#     powerOffDialog.show()
#     sys.exit(app.exec_())
