# coding=utf-8
from view.setting.personalizedsetting import Ui_Form
from PyQt4.QtGui import QDialog
from PyQt4.QtCore import SIGNAL, QString, Qt
from common.logrecord import LogRecord
from common.infohintdialog import InfoHintDialog
from model.setting.screenset import ScreenSet
from model.setting.multimonitor import MultiMonitor
from common.messagebox import MessageBox
from model.setting.personalizedset import PersonalizedSet
from PyQt4.Qt import QWidget

 
class PersonalizedSetting(QWidget, Ui_Form):
    def __init__(self):
        super(PersonalizedSetting, self).__init__()
        self.setupUi(self)
        
        self.personalizedSet=PersonalizedSet()
        self.screenSet = ScreenSet()
        self.multiMonitor = MultiMonitor()
        
        self.resolutionAutoAdjust()  # 分辨率自适应初始化
        self.screensaveStatus()
        self.setMultiMonitorStatus()
        self.screenStatus()
        self.updateVmSereenState()#更新配置是否关机退出虚拟机全屏函数

        
        self.connect(self.radioButtonResolutionStart, SIGNAL("clicked()"), self.on_radioButtonOpenAutoAdjust_clicked)
        self.connect(self.radioButtonResolutionStop, SIGNAL("clicked()"), self.on_radioButtonCloseAutoAdjust_clicked)
        self.connect(self.radioButtonNoStartScreenSet, SIGNAL("clicked()"), self.on_radioButtonStartScreen_clicked)
        self.connect(self.radioButtonNoStopScreenSet, SIGNAL("clicked()"), self.on_radioButtonCancelScreen_clicked)
        self.connect(self.radioButtonStartTwoScreenDif, SIGNAL("clicked()"), self.on_radioButtonEnableMulti_clicked)
        self.connect(self.radioButtonStartTwoScreenComb, SIGNAL("clicked()"), self.on_radioButtonMulConnect_clicked)
        self.connect(self.radioButtonStartTwoScreenTime,SIGNAL("clicked()"),self.on_radioButtonDisableMulti_clicked)
        self.connect(self.screenComboBox, SIGNAL("activated(int)"), self.slotScreenSolution)
        self.connect(self.pushButtonPersonSet, SIGNAL("clicked()"), self.onPushButtonSetClicked)
        self.connect(self.radioButtonOpenSereenFun,SIGNAL("clicked()"),self.radioButtonOpenSereen_clicked)
        self.connect(self.radioButtonCloseSereenFun,SIGNAL("clicked()"),self.radioButtonCloseSereen_clicked)
        
        self.setStyleSheet(QString("QComboBox{border:1px groove rgb(170,214,252);height:25;}"))
    
    def radioButtonOpenSereen_clicked(self):
        if (MessageBox(u"选择该项将不会启用双屏显示功能！是否继续此操作？").exec_() == QDialog.Accepted):
            self.personalizedSet.setVmScreenState("yes")
        else:
            self.updateVmSereenState()
    def radioButtonCloseSereen_clicked(self):
        self.personalizedSet.setVmScreenState("no")
    
    def updateVmSereenState(self):
        retv=self.personalizedSet.updateVmScreenState()
        if(retv!=None):
            if(retv=="yes"):
                self.radioButtonOpenSereenFun.setChecked(True)
            elif(retv=="no"):
                self.radioButtonCloseSereenFun.setChecked(True)
        else:
            self.radioButtonOpenSereenFun.setChecked(True)
            self.personalizedSet.setVmScreenState("yes")
    
    def onPushButtonSetClicked(self):
        LogRecord.instance().recordLog(u"分辨率设置按钮")
        screenName = self.screenComboBox.currentText()
        reScreen = self.ratioComboBox.currentText()
        curSysResolution = self.screenSet.getCurScreen(screenName)
        if (not screenName.isNull() and not screenName.isEmpty() and not reScreen.isEmpty() and not reScreen.isNull()):
            self.screenSet.setCurrentScreenName(screenName)
            self.screenSet.setCurrentScreenResolution(curSysResolution)
            ok = self.screenSet.setCurScreen(screenName, reScreen)
            if (ok):
                # 调节窗口的位置setscreenover
                self.emit(SIGNAL("ResolutionSet"))
                # 开启定时器，十秒钟后恢复原来的屏幕分辨率
                self.screenSet.controlTimer("start")
                # 弹出提示框，默认为取消
                if (MessageBox(u"确定设置为当前选择的分辨率?").exec_() == QDialog.Accepted):
                    # 关闭定时器，禁止回复原来的分辨率
                    self.screenSet.controlTimer("stop")
                    res = self.screenSet.setResolutionFile(screenName, reScreen)
                    if (res == -1):
                        InfoHintDialog(u"打开屏幕分辨率文件失败").exec_()
                    elif (res == -2):
                        InfoHintDialog(u"删除屏幕分辨率文件中指定的条目失败").exec_()
                    # 判断配置文件是否是多屏拼接
                    if (self.multiMonitor.isMultiConnect()):
                        # 判断各个屏幕的分辨率是否相同
                        if (not self.isResolutionSame()):
                            InfoHintDialog(u"双屏组合显时多屏幕分辨率必须相同!").exec_()
                            return
                            
                    self.emit(SIGNAL("setscreenover"))
                    return
                else:
                    self.screenSet.resetResolution()
#                     self.screenStatus()
                    return
        return
    
    def slotScreenSolution(self, index):
        self.ratioComboBox.clear()
        LogRecord.instance().recordLog(u"切换显示器显示分辨率下拉列表")
        screenlist = self.resolutionMap[str(self.screenComboBox.currentText())]
        self.ratioComboBox.addItems(screenlist)
        for i in range(self.screenComboBox.count()):
            screenName = self.screenComboBox.itemText(i)
            curscr = self.screenSet.getCurScreen(screenName)
            if (self.screenComboBox.currentText() == screenName):
                self.ratioComboBox.setCurrentIndex(self.ratioComboBox.findText(curscr))

    def screenStatus(self):
        LogRecord.instance().recordLog(u"显示器读取")
        aMonitors = self.screenSet.getMonitors("xrandr | awk '{ if($2 ~ \"connected\") {print $1 \" \" $2 \" \" NR}}'")        
        self.resolutionMap = {}
        Monitors = []
        acount = len(aMonitors)
        for j in range(acount):
            if len(aMonitors[j].split(" ")) == 3:  # 得到正确的输出
                Monitors.append(aMonitors[j])
               
        count = len(Monitors)
        for i in range(count):
                rowStopNumber = ""
                rowStartNumber = ""
                monitorName = Monitors[i].split(" ")[0]
                linkStatus = Monitors[i].split(" ")[1]
                rowStartNumber = Monitors[i].split(" ")[2]
                
                if (linkStatus == "disconnected"):
#                     print "disconnect"
                    continue
                if (i != count - 1):
                    rowStopNumber = Monitors[i + 1].split(" ")[2]
#                 print rowStartNumber
#                 print rowStopNumber
                if (rowStopNumber == "" or rowStopNumber == rowStartNumber):
                    resolutionCmd = "xrandr | awk '{ if(NR > " + rowStartNumber + ")" + "{print $1}}'"
                else:
                    resolutionCmd = "xrandr | awk '{ if((NR > " + rowStartNumber + ") && (NR < " + rowStopNumber + "))" + "{print $1}}'"
        
                resolutionList = []
                lastResolutionList = []
#                 print resolutionCmd
                resolutionList = self.screenSet.getMonitors(resolutionCmd)
                
                num = len(resolutionList)
                for i in range(num):
                    if (len(resolutionList[i].split("x")) > 1 and len(resolutionList[i].split(" ")) < 2):
                        lastResolutionList.append(resolutionList[i])
                self.resolutionMap[monitorName] = lastResolutionList
        self.screenComboBox.clear()
        index = 0
        for key in self.resolutionMap:
            name = key
            reList = self.resolutionMap[key]
            self.screenComboBox.addItem(name)
            self.screenComboBox.setItemData(index, reList, Qt.UserRole + 1)
            index += 1
            
        curretIndex = self.screenComboBox.currentIndex()
        screenName = self.screenComboBox.itemText(curretIndex)
        variant = self.screenComboBox.itemData(curretIndex, Qt.UserRole + 1)
        
        if (variant.isValid()):
            self.ratioComboBox.clear()
            reList = variant.toStringList()
            count = len(reList)
            for i in range(count):
                self.ratioComboBox.addItem(reList[i])
    
        # 显示当前屏幕的分辨率
        curscr = self.screenSet.getCurScreen(screenName)
        j = self.ratioComboBox.count()
        for i in range(j):
            if(curscr == self.ratioComboBox.itemText(i)):
                self.ratioComboBox.setCurrentIndex(i)

    def setMultiMonitorStatus(self):  # 多显示器按钮状态初始化(多屏设置初始化
        LogRecord.instance().recordLog(u"多屏幕读取")
        status = self.multiMonitor.getMultiMonitorStatus()
        if(QString(status).startsWith("enable")):
            if (status.split(":")[1] == "None"):
                self.radioButtonStartTwoScreenDif.setChecked(True)
            else:
                self.radioButtonStartTwoScreenComb.setChecked(True)
        else:
            self.radioButtonStartTwoScreenTime.setChecked(True)
            
    def on_radioButtonDisableMulti_clicked(self):  # 启动双屏同显
#         print "爽平同显示"
        if (not self.isResolutionSame()):
            InfoHintDialog(u"各个屏幕必须设置成相同的分辨率!").exec_()
            return
        LogRecord.instance().recordLog(u"取消多屏幕")
        result = self.multiMonitor.disableMultiMonitor()
        if(result == -1):
            InfoHintDialog(u"没有检测到多个显示器").exec_()
        elif(result == -2):
            InfoHintDialog(u"获取显示器失败").exec_()
        else:
            InfoHintDialog(u"启动双屏同显成功!").exec_()
            self.emit(SIGNAL("setscreenover"))
    
    def on_radioButtonMulConnect_clicked(self):  # 启动双屏组合显
        result = self.multiMonitor.enableMultiMonitor()
        if(result == -1):
            InfoHintDialog(u"没有检测到多个显示器").exec_()
            return
        if(result == -2):
            InfoHintDialog(u"获取显示器失败").exec_()
            return
        if(result == -3):
            InfoHintDialog(u"获取当前分辨率失败").exec_()
            return
        if (not self.isResolutionSame()):
            InfoHintDialog(u"各个屏幕必须设置成相同的分辨率!").exec_()
            return
        screenName = self.screenComboBox.itemText(0)
        firstScreenCursor = self.screenSet.getCurScreen(screenName)
        # 获得多屏的分辨率
        width = int(firstScreenCursor.split("x")[0]) * 2
        height = firstScreenCursor.split("x")[1]
        ssize = QString.number(width) + "x" + height
        # 把支持多屏连接的分辨率写入文件
        self.multiMonitor.setMultiMonitorStatus("enable", ssize)
        InfoHintDialog(u"启用多屏拼接成功!").exec_()
#         self.emit(SIGNAL("setscreenover"))
        return
    
    
    def on_radioButtonEnableMulti_clicked(self):  # 启动双屏异显
#         print "yes"
        if (not self.isResolutionSame()):
            InfoHintDialog(u"各个屏幕必须设置成相同的分辨率!").exec_()
            return
        LogRecord.instance().recordLog(u"多屏幕设置")
        result = self.multiMonitor.enableMultiMonitor()
        if(result == -1):
            InfoHintDialog(u"没有检测到多个显示器").exec_()
        elif(result == -2):
            InfoHintDialog(u"获取显示器失败").exec_()
        elif(result == -3):
            InfoHintDialog(u"获取当前分辨率失败").exec_()
        else:
            InfoHintDialog(u"启动双屏异显成功!").exec_()
#             self.emit(SIGNAL("setscreenover"))
        
        
    def screensaveStatus(self):  # 屏保设置初始化
        LogRecord.instance().recordLog(u"屏保文件读取")
        screen_status = self.screenSet.screensaveStatus()
        if(screen_status == "enable"):
            self.radioButtonNoStartScreenSet.setChecked(True)
        elif(screen_status == "disable"):
            self.radioButtonNoStopScreenSet.setChecked(True)
        elif (screen_status == None):
            self.screenSet.ctrlScreenSave("off")
        
        
    def on_radioButtonCancelScreen_clicked(self):  # 屏保取消
        LogRecord.instance().recordLog(u"屏保取消按钮")
        res = self.screenSet.ctrlScreenSave("off")
        if(-1 == res):
            InfoHintDialog(u"打开屏保文件失败").exec_()
            return
        elif(-2 == res):
            InfoHintDialog(u"关闭屏保失败").exec_()
            return
        else:
            InfoHintDialog(u"成功禁用终端屏保").exec_()
            return
        return
        
    def on_radioButtonStartScreen_clicked(self):  # 屏保开启
        LogRecord.instance().recordLog(u"屏保设置按钮")
        res = self.screenSet.ctrlScreenSave("start")
        if(-1 == res):
            InfoHintDialog(u"打开屏保文件失败").exec_()
            return
        elif(-2 == res):
            InfoHintDialog(u"启用屏保失败").exec_()
            return
        else:
            InfoHintDialog(u"成功启用终端屏保").exec_()
            return
        return

    def resolutionAutoAdjust(self):  # 分辨率自适应初始化函数
        LogRecord.instance().recordLog(u"分辨率自适应读取")
        action = self.screenSet.getResolutionAutoAdjustType()
        if (action == "open"):
            self.radioButtonResolutionStart.setChecked(True)
            self.screenSet.ctrlResolutionAutoAdjust("open")
        elif action == "close":
            self.radioButtonResolutionStop.setChecked(True)
            self.screenSet.ctrlResolutionAutoAdjust("close")
        else:
            self.screenSet.ctrlResolutionAutoAdjust("open")
            self.radioButtonResolutionStart.setChecked(True)


    def on_radioButtonOpenAutoAdjust_clicked(self):  # 分辨率自适应打开
#         print "dddd"
        LogRecord.instance().recordLog(u"分辨率自适应设置按钮")
        res = self.screenSet.ctrlResolutionAutoAdjust("open")
        if(-1 == res):
            InfoHintDialog(u"打开分辨率自适应文件失败").exec_()
        elif(-2 == res):
            InfoHintDialog(u"设置环境变量SMEP_SEND_MONITOR_CONFIG失败").exec_()
        else:
            InfoHintDialog(u"成功启用分辨率自适应").exec_()
        return

    def on_radioButtonCloseAutoAdjust_clicked(self):  # 分辨率自适应关闭
#         print "yessss"
        LogRecord.instance().recordLog(u"取消分辨率自适应按钮")
        res = self.screenSet.ctrlResolutionAutoAdjust("close")
        if(-1 == res):
            InfoHintDialog(u"打开分辨率自适应文件失败").exec_()
        else:
            InfoHintDialog(u"成功关闭分辨率自适应").exec_()
        return
    
        # 判断各个屏幕的分辨率是否相同
    def isResolutionSame(self):
        resolutionMap = {}
        for i in range(self.screenComboBox.count()):
            screenName = self.screenComboBox.itemText(i)
            curscr = self.screenSet.getCurScreen(screenName)
            if (i == 0):
                firstScreenCursor = curscr
            resolutionMap[screenName] = curscr
        for item in resolutionMap:
            if resolutionMap[item] != firstScreenCursor:
                return False
        return True
    
