#!/usr/bin/python
#coding=utf-8

from logger.logrecord import LogRecord

from PyQt4 import QtCore
from PyQt4 import QtGui
from threading import Thread
import time
import usb1
import os


class DetectUSB(QtCore.QObject):
    """
    监测USB设备插拔动作
    """
    __instance = None
    def __init__(self):
        QtCore.QObject.__init__(self)
        self.__running = False
        self.USBPulginSignal = QtCore.pyqtSignal()

    def __hotplug_callback(self,context, device, event):
        """
        当USB设备插入，发出信号
        :param context:
        :param device:
        :param event:
        :return:
        """
        if event == usb1.HOTPLUG_EVENT_DEVICE_ARRIVED:
            LogRecord.instance().logger.debug("Device arrived:[%s %s %s]\n" %(device, device.getManufacturer(), device.getProduct()))
            # self.emit(QtCore.SIGNAL('USBPulginSignal'))
            #add by pbc for usb status
            from common import common_run
            if common_run.usb_status == "network_ip":
                self.emit(QtCore.SIGNAL('USBPulginSignal'))
        else:
            LogRecord.instance().logger.debug("Device left:[%s]\n" %(device))

    def __runDetect(self):
        """
        监测USB状态
        :return:
        """
        with usb1.USBContext() as context:
            if not context.hasCapability(usb1.CAP_HAS_HOTPLUG):
                LogRecord.instance().logger.debug('Hotplug support is missing. Please update your libusb version.')
                return
            opaque = context.hotplugRegisterCallback(self.__hotplug_callback)
            try:
                while self.__running:
                    context.handleEvents()
                    time.sleep(0.01)
            except (KeyboardInterrupt, SystemExit):
                pass
        LogRecord.instance().logger.debug("USB监测线程退出！")

    def start(self):
        """
        启动USB监测线程
        :return:
        """
        if (DetectUSB.__instance != None and
            DetectUSB.__instance != self):
            try:
                DetectUSB.__instance.stop()
                DetectUSB.__instance = None
            except Exception,err:
                LogRecord.instance().logger.debug("关闭原usb接口监控线程异常！")
                return
        if (DetectUSB.__instance == None):
            DetectUSB.__instance = self

        if not self.__running:
            LogRecord.instance().logger.debug("启动USB监测线程！")
            self.__running = True
            self.__detThread = Thread(target=self.__runDetect)
            self.__detThread.setDaemon(True)
            self.__detThread.start()
        else:
            LogRecord.instance().logger.debug("USB监测线程正在运行！")

    def stop(self):
        """
        停止USB监测线程
        :return:
        """
        if self.__running:
            LogRecord.instance().logger.debug("关闭USB监测线程！")
            self.__running = False
            self.__detThread.join(1)
            DetectUSB.__instance = None
        else:
            LogRecord.instance().logger.debug("USB监测线程没有运行！")


class USBMessageBox(QtGui.QDialog):
    __instance = None
    @classmethod
    def showMsg(cls,msg):
        if USBMessageBox.__instance == None:
            USBMessageBox.__instance = USBMessageBox()

        USBMessageBox.__instance.refresh()
        USBMessageBox.__instance.contentLabel.setText(msg)
        USBMessageBox.__instance.show()

        try:
            import virtkey
            v = virtkey.virtkey()
            v.press_keysym(65507)#ctrl-l
            v.press_keysym(65513)#Alt_L
            v.release_keysym(65513)
            v.release_keysym(65507)
        except Exception,err:
            LogRecord.instance().logger.exception('ctrl+alt')


    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setModal(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.__imagePath=os.getenv('WIN_UI_IMAGES_PATH')

        self.setStyleSheet("QDialog{background-color:rgba(230,230,230,255);}")

        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(u"  提示")

        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.setAlignment(QtCore.Qt.AlignCenter)
        self.contentLabel.setWordWrap(True)
        self.contentLabel.setText(u'USB设备透传连接异常！\n（按“Ctrl+Alt”键，从虚拟机中释放鼠标）')

        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.OKBtn=QtGui.QPushButton(self.bottomLabel)
        self.bottomLabel.OKBtn.setFlat(True)
        self.bottomLabel.OKBtn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.bottomLabel.OKBtn.setText(u'确定')

        self.connect(self.topLabel.closePushButton,QtCore.SIGNAL("clicked()"),self,QtCore.SLOT('onCloseBtn()'))
        self.connect(self.bottomLabel.OKBtn,QtCore.SIGNAL("clicked()"),self,QtCore.SLOT('onCloseBtn()'))

    def refresh(self):
        self.__getResolution()

        self.__width = 2 * self.__screen_width / 5
        self.__height = self.__width *2.0 / 5.0
        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((self.__screen_width-self.__width)/2.0,
                         (self.__screen_height-self.__height)/2.0,
                         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.topLabel.closePushButton.setGeometry(self.topLabel.width()-self.__topHeight*16//15,0,self.__topHeight*16//15,self.__topHeight)

        contentFont=QtGui.QFont()
        contentFont.setPointSize(12.0*1440/self.__screen_width)
        self.contentLabel.setFont(contentFont)
        # self.contentLabel.setText(u'查询usbip的连接状态，确定是否重连')
        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.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)
        okFont = QtGui.QFont()
        okFont.setPointSize(12.0*1440/self.__screen_width)
        self.bottomLabel.OKBtn.setFont(okFont)
        self.bottomLabel.OKBtn.setGeometry((self.__width-self.__width/4.0)/2.0,
                                           self.__bottomHeight/8.0,
                                           self.__width/4.0,
                                           3.0*self.__bottomHeight/4.0)
        self.bottomLabel.OKBtn.setStyleSheet("QPushButton{border-image:url(%s/settingWindow/pushbutton.png);background:transparent;color:white;}"%self.__imagePath+
                                                    "QPushButton:hover{border-image:url(%s/settingWindow/pushbutton_hov.png);background:transparent;color:white;}"%self.__imagePath+
                                                   "QPushButton:pressed{border-image:url(%s/settingWindow/pushbutton_pre.png);background:transparent;color:white;}"%self.__imagePath)


    def __getResolution(self):
        cmd = "xrandr | grep \"^  .*x.*\*\" | sed  \"s/^\ \ \ //g\" | sed \"s/\ .*$//\""
        try:
            f = os.popen(cmd, "r")
            Resolution = f.readline().strip('\n')  # 去掉\n
            f.close()
            width,height=Resolution.split('x',1)
            self.__screen_width=int(width)
            self.__screen_height=int(height)
            return
        except Exception:
            desktop=QtGui.QApplication.desktop()
            self.__width=desktop.width()
            self.__height=desktop.height()
            return

    @QtCore.pyqtSlot()
    def onCloseBtn(self):
        self.hide()

    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()

    def keyPressEvent(self,event):
        if (event.key() == QtCore.Qt.Key_Enter) or (event.key() == QtCore.Qt.Key_Return):
            self.onCloseBtn()


if __name__ == "__main__":
    import sys
    from PyQt4 import QtGui
    from os import  environ
    os.environ["WIN_UI_IMAGES_PATH"]="../../images"
    environ["LOG_STDOUT"] = "stdout"  #
    app = QtGui.QApplication(sys.argv)

    det = DetectUSB()
    det.start()

    USBMessageBox.showMsg(u'USB设备透传连接异常！\n（请按“Ctrl+Alt”键，从虚拟机中释放鼠标）')
    sys.exit(app.exec_())