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

@author: root
'''
import os
import commands

from PyQt4.QtCore import QObject, QString

from model.cfg.storeinfoparser import StoreInfoParser
from common.logrecord import LogRecord

class MultiMonitor(QObject):
    _instance = 0
    def __init__(self,parent=None):
        super(MultiMonitor,self).__init__(parent)
        
    
    @classmethod 
    def instance(cls):
        if (cls._instance == 0):
            cls._instance = MultiMonitor()
            
        return cls._instance

    #获取 命令行 的执行结果
    def execCmd(self,command):
        """
        FILE * fp;
        char buffer[1024];
        QString str
        QStringList temp ,result
        fp = popen(cmd,"r")
    
        while(!feof(fp))
        
            if(fgets(buffer,sizeof(buffer)-1,fp) != NULL)
            
                str = buffer
                temp =  str.split("\n")
                result.append(temp[0])
        pclose(fp)
        """
        #得到命令行标准输出：
        statusOutput = []
        output = ""
        statusOutput = commands.getstatusoutput(command)
        if statusOutput[0] == 0:#如果是0，则执行成功
            output = statusOutput[1]#第二个元素就是命令行执行后的输出
        #return output
        else:
            output = ""
            
        result = output.split("\n")
        
        return result
    
    #获取显示器
    def getActiveMonitors(self):
    
        #QStringList monitorList, temp;
        monitorList = []
        temp = self.execCmd("xrandr |awk '/connected/'")
        #for(int i = 0; i < temp.size(); i++)
        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                monitorList.append(temp[i].split(" ")[0]);
        #qDebug() << monitorList;
        return monitorList
    
    
    #获取分辨率
    def getCurrentResolution(self):
    
        #QStringList temp
        #QString resolution
        temp = self.execCmd("xrandr |awk '/connected/'");
    
        #for(int i = 0; i < temp.size(); i++)
        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                resolution = temp[i].split(" ")[2]
        #qDebug() << resolution;
        return resolution
    
    
    #启用多显示器(双平异显）
    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]
    
        cmd = "xrandr --auto --output " + monitorsList[0] + " --mode " + resultion
        for i in range(1,len(monitorsList)):
        #for(int i = 1; i < monitorsList.size(); i++)
            cmd += " --left-of " + monitorsList[i]
            LogRecord.instance().recordLog(cmd)
#         qDebug() << cmd;
        os.system(cmd)
        self.setMultiMonitorStatus("enable","None")
        
        return 0
    def getMulCurrentResolution(self):
    
        #QStringList temp
        #QString resolution
        temp = self.execCmd("xrandr |awk '/connected/'");
        resolutionList = []
        #for(int i = 0; i < temp.size(); i++)
        for i in range(len(temp)):
            if(temp[i].split(" ")[1] == "connected"):
                resolution = temp[i].split(" ")[2]
                resolutionList.append(resolution)
        #qDebug() << resolution;
        return resolutionList
    
    #禁用多显示器
    def disableMultiMonitor(self):
        #QStringList monitorsList
        #QString cmd, cmdTemp, resultion
        monitorsList = self.getActiveMonitors()
        if(len(monitorsList) == 1):
            return -1
        if(len(monitorsList) == 0):
            return -2
        resultionList = self.getMulCurrentResolution()
        #resultion = self.getCurrentResolution()
        if(len(resultionList) == 0):
            return -3
        resultion = resultionList[0].split("+")[0]
        
        #resultion = resultion.split("+")[0]
        cmd = "xrandr "
        for i in range(1,len(monitorsList)):
        #for(int i = 1; i < monitorsList.size(); i++)
            cmdTemp = cmd + " --output " + monitorsList[i] + " --off "
            cmd = cmd + " --output " + monitorsList[i] +  " --mode " + resultionList[i].split("+")[0]
#             LogRecord.instance().recordLog(cmdTemp)
#             LogRecord.instance().recordLog(cmd)
        #qDebug() << cmd;
        os.system(cmdTemp)
        os.system(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
    
    
    def setMultlMonitor(self):
        """
        设置多屏幕显示
        """
        status = self.getMultiMonitorStatus()
        monitorsList = self.getActiveMonitors()
    
        if(len(monitorsList) > 1 and QString(status).startsWith("enable") ):
            result = self.enableMultiMonitor()
            if(result == -1):
                self.disableMultiMonitor()
            elif(result == -2):
                self.disableMultiMonitor()
            elif(result == -3):
                self.disableMultiMonitor()
        elif (len(monitorsList) > 1 and not QString(status).startsWith("enable") ):
            self.disableMultiMonitor()
        else:
            return



