#coding:utf-8
'''
Created on Sep 17, 2014

@author: root
'''
import commands
import os

from base.storeinfoparser import StoreInfoParser
from logger.logrecord import LogRecord


class MultiMonitor(object):
    def __init__(self,parent=None):
        super(MultiMonitor,self).__init__()

    #获取 命令行 的执行结果
    def execCmd(self,command):
 
        #得到命令行标准输出：
        output = ""
        statusOutput = commands.getstatusoutput(command)
        if statusOutput[0] == 0:#如果是0，则执行成功
            output = statusOutput[1]#第二个元素就是命令行执行后的输出
        #return output
        else:
            output = ""
            
        result = output.split("\n")
        
        return result

    #获取 命令行 的执行结果
    @classmethod
    def execUnixCmd(cls,command):

        #得到命令行标准输出：
        output = ""
        statusOutput = commands.getstatusoutput(command)
        if statusOutput[0] == 0:#如果是0，则执行成功
            output = statusOutput[1]#第二个元素就是命令行执行后的输出
        #return output
        else:
            output = ""

        result = output.split("\n")

        return result



    #获取当前连接的显示器
    @classmethod
    def getCurActiveMonitors(cls):

        #QStringList monitorList, temp;
        monitorList = []
        # temp = self.execCmd("xrandr |awk '/connected/'")
        temp = cls.execUnixCmd("xrandr |awk '/connected/'")

        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                monitorList.append(temp[i].split(" ")[0]);

        return monitorList


    #获取当前连接的显示器
    def getActiveMonitors(self):
    
        #QStringList monitorList, temp;
        monitorList = []
        temp = self.execCmd("xrandr |awk '/connected/'")
       
        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                monitorList.append(temp[i].split(" ")[0]);

        return monitorList

    @classmethod
    def setSingelMonitors(cls):
        try:
            monitorsList  = cls.getCurActiveMonitors()
            print str(monitorsList)
            if len(monitorsList) > 1 :
                for i in range(len(monitorsList)):
                    if i > 0:
                        cmd = "xrandr --output %s --off "% monitorsList[i]
                        os.system(cmd)  # 关闭 屏幕
            else:
                pass
            # print "setSingelMonitors seccess"
            return 0
        except Exception:
            # print "setSingelMonitors Exception"
            return -1


    #获取分辨率
    def getCurrentResolution(self):
    
     
        temp = self.execCmd("xrandr |awk '/connected/'");
        # temp = self.execCmd("xrandr |awk '/primary/'");

        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                resolution = temp[i].split(" ")[2]
       
        return resolution

    def enableSameDoubleMonitor(self):

        monitorsList = self.getActiveMonitors()
        if(len(monitorsList) == 1):
            return -1
        if(len(monitorsList) == 0):
            return -2
        resultionList = self.getMulCurrentResolution()
        if(len(resultionList) == 0):
            return -3
        resultion = resultionList[0].split("+")[0]


        cmd = "xrandr --output %s --off "% monitorsList[1]
        os.system(cmd)  # 关闭双屏

        # cmd = "xrandr --auto  --output " + monitorsList[0] + " --mode " + resultion
        cmd = "xrandr --output %s --auto "% monitorsList[1]

        # 写日志文件
        # for i in range(1,len(monitorsList)):
        #
        #     cmd += " --left-of " + monitorsList[i]
        #     LogRecord.instance().logger.info(str(cmd))

        os.system(cmd)
        self.setMultiMonitorStatus("enable","None")

        return 0
    
    #启用多显示器(双平异显）
    def enableMultiMonitor(self):

        monitorsList = self.getActiveMonitors()
        if(len(monitorsList) == 1):
            return -1
        if(len(monitorsList) == 0):
            return -2
        resultionList = self.getMulCurrentResolution()
        if(len(resultionList) == 0):
            return -3
        resultion = resultionList[0].split("+")[0]

        # "xrandr --output VGA1 --auto --right-of LVDS1 --primary" # 主屏幕VGA1  ,
        # "xrandr --output VGA1 --auto --right-of LVDS1"            # 主屏幕LVDS1, VGA1 位于 右边
        #  xrandr --output VGA1 --auto --right-of LVDS1 --mode 800x600

        # cmd = "xrandr --auto  --output " + monitorsList[0] + " --mode " + resultion
        cmd = "xrandr --output %s --auto --right-of %s "% (monitorsList[1],monitorsList[0])
        # print cmd
        # for i in range(1,len(monitorsList)):
        #
        #     cmd += " --left-of " + monitorsList[i]
        #     LogRecord.instance().logger.info(str(cmd))

        os.system(cmd)
        self.setMultiMonitorStatus("enable","None")
        
        return 0
    def getMulCurrentResolution(self):
    

        temp = self.execCmd("xrandr |awk '/connected/'");
        resolutionList = []
       
        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                resolution = temp[i].split(" ")[2]
                resolutionList.append(resolution)

        return resolutionList
    
    #禁用多显示器
    def disableMultiMonitor(self):

        monitorsList = self.getActiveMonitors()
        if(len(monitorsList) == 1):
            return -1
        if(len(monitorsList) == 0):
            return -2
        resultionList = self.getMulCurrentResolution()

        if(len(resultionList) == 0):
            return -3
 
        cmd = "xrandr "

        for i in range(1,len(monitorsList)):
      
            cmdTemp = cmd + " --output " + monitorsList[i] + " --off "
            cmd = cmd + " --output " + monitorsList[i] +  " --mode " + resultionList[i].split("+")[0]
            LogRecord.instance().logger.info(cmdTemp)
            LogRecord.instance().logger.info(cmd)
        # print cmdTemp
        # print cmd
        os.system(cmdTemp)
        # os.system(cmd)
      
        self.setMultiMonitorStatus("disable","None")
        return 0
    #读配置文件 获取按钮状态
    def getMultiMonitorStatus(self):

        result = StoreInfoParser.instance().getMultiMonitor()
        return result
    
    #写配置文件 设置按钮状态
    def setMultiMonitorStatus(self,canable,value):

        setinput = canable + ":" + value
        StoreInfoParser.instance().setMultiMonitor(setinput)
    
    
    def isMultiConnect(self):
    
        value = self.getMultiMonitorStatus()
        if (len(value) == 0):
            return False
    
        if (value.split(":")[1] == "disable" or value.split(":")[1] == "None"):
            return False

        return True
    


if __name__ == "__main__":
    import sys
    from PyQt4.QtGui import QApplication
    app = QApplication(sys.argv)
    mutimonitor = MultiMonitor()
    print"curren", mutimonitor.getCurrentResolution() # 获取当前分辨率
    print mutimonitor.getActiveMonitors()

    print mutimonitor.enableMultiMonitor() #启用多显示器(双平异显）
    # print mutimonitor.enableSameDoubleMonitor()  #启用多显示器(双平同显）
    # print mutimonitor.disableMultiMonitor()

    #app.exec_()