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

@author: root
'''

import commands
import os

from PyQt4.QtCore import QTimer, Qt, SIGNAL, QObject, QString

from base.storeinfoparser import StoreInfoParser
from common import syscfg

class ScreenSet(QObject):
    def __init__(self,parent=None):
        super(ScreenSet,self).__init__(parent)
        self.timer = QTimer()
        self.connect(self.timer,SIGNAL("timeout()"),self.restoreResolution,Qt.QueuedConnection)
    
    def controlTimer(self,ctrl):
        if (ctrl == "start"):
            self.timer.start(10*1000)
        elif (ctrl == "stop"):
            self.timer.stop()
    
    def getTimer(self):
        return self.timer
    
    def toList(self,listStr):
        listT = []
        listS = "a"
        if(type(listStr) == type(listS)):
            listList = []
            list = listStr.split(",")
            for i in range(len(list)):
                listList.append(list[i].split("'")[1])
            return listList
        elif(type(listStr) == type(listT)):
            return listStr  
        return []  
    
    def setResolutionFile(self,screenName,newResolution):


        item = screenName + ":" + newResolution
 
        StoreInfoParser.instance().setScreen(item)
        return 0
    
    def restoreResolution(self):
        name = self.curScreenName
        resolution = self.screenResolution
        self.timer.stop()
        if (name != "" and resolution != ""):
            self.setCurScreen(name, resolution)
            
        self.emit(SIGNAL("ResolutionSet"))
    
    def resetResolution(self):
        self.restoreResolution()
    
    def setCurrentScreenName(self,name):
        self.curScreenName = name
    
    def setCurrentScreenResolution(self,resolution):
        self.screenResolution = resolution
    
    
    def screensaveStatus(self):
        return syscfg.screen_info('screensaver')
    
    #启用/禁用屏保
    def ctrlScreenSave(self,action):
     
        if(action == "start"):
            os.system("xset s on")
            status = os.system("xset +dpms")
            if(-1 != status):
                s = "enable"
                
                StoreInfoParser.instance().setScreenSaver(s)
                return 0
            else:
             
                return -2
        elif(action == "off"):
            os.system("xset s off");
            status = os.system("xset -dpms")
            if(-1 != status):
                s = "disable"
               
                StoreInfoParser.instance().setScreenSaver(s)
                return 0
            else:
               
                return -2
    
    #读取当前分辨率
    def getCurScreen(self,screenName):
  
        curScrCmd = "xrandr | awk '{ if(($1 == \"" + screenName + "\") && " +  "($2 == \"connected\"))  {print $3}}'"
        curscrList = self.getMonitors(str(curScrCmd))
       
        curscr = ""
        
        if len(curscrList) == 2:
            curscr = curscrList[1].split("+")[0]
            return curscr
        elif(len(curscrList) == 1):
            curscr = curscrList[0].split("+")[0]
            return curscr
        return curscr
    #设置分辨率
    def setCurScreen(self,screenName,reScreen):
  
        cmd = QString("xrandr ") + " --output " + screenName + " --mode " + reScreen
        
        sysFlag = os.system(str(cmd))
        if(0 == sysFlag):
    
            return True
        return False
    
    def ctrlResolutionAutoAdjust(self,action):
        
        if(action == "open"):
           
            self.setSmepEnvOn()

            
            
            s = "ON"
         
            StoreInfoParser.instance().setAutoAdjust(s)
            return 0
        elif(action == "close"):
           
            self.setSmepEnvOff()
          
            s = "OFF"
    
            StoreInfoParser.instance().setAutoAdjust(s)
            return 0
    
    def getResolutionAutoAdjustType(self):

        current_text = StoreInfoParser.instance().getAutoAdjust()
     
        if (current_text == "ON"):
            return "open"
        elif(current_text == "OFF"):
            return "close"
        else:
            return ""
    #获取连接或未连接的显示器
    
    
    def getMonitors(self,cmd):
        temp = self.execCmd(str(cmd))
        return temp
    def execCmd(self,command):
       
        print ("output253")
        #得到命令行标准输出：

        output = ""
        print ("output257")
        statusOutput = commands.getstatusoutput(command)

        if statusOutput[0] == 0:#如果是0，则执行成功
            output = statusOutput[1]#第二个元素就是命令行执行后的输出
        else:
            output = ""

        result = output.split("\n")
        return result
    def setSmepEnvOn(self):
        
     
        os.environ["SMEP_SEND_MONITOR_CONFIG"] = "ON"

#         
    def setSmepEnvOff(self):
         
      
        os.environ["SMEP_SEND_MONITOR_CONFIG"] = "OFF"

        
        
    def updateVmScreenState(self):
        retv=StoreInfoParser.instance().getAutoVmScreenState()
        return retv
        
    def setVmScreenState(self,stateV):
        StoreInfoParser.instance().setAutoVmScreenState(stateV)
        
        
        
        
        
    