#coding:utf-8


from PyQt4.QtCore import QString, QStringList, QFile
from PyQt4.QtGui import QApplication
import os, commands
from model.cfg.storeinfoparser import StoreInfoParser
from model.setting.multimonitor import MultiMonitor


    
def moveWidgetToScreenCenter(widget, checkMulMonitor=True):
    """
    移动控件到屏幕中心
    """
    desktop = QApplication.desktop()
    width = desktop.width()
    height = desktop.height()
    
    status = StoreInfoParser.instance().getMultiConnectState()
    monitorsList = getActiveMonitors()
    if len(monitorsList) > 1 and status and QString(status).startsWith("enable"):
        width = width / len(monitorsList)
    widget.move((width - widget.width())/2,  (height - widget.height())/2)
    

    
def getVersionAndReleaseDate():
    """获取版本信息"""
    version = None
    rDate = None
    if os.path.exists("/etc/default/version"):
        statusOutput = commands.getstatusoutput("cat /etc/default/version")
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "VERSION":
                    version = value.split("=")[1]
                if value.split("=")[0] == "BUILD_DATE":
                    rDate = value.split("=")[1]
                    
    return version

def setMultiMonitor():
    """
        设置多屏幕显示
    """
    MultiMonitor.instance().setMultlMonitor()

def setScreenGuard():
    """
    设置屏幕保护
    """
    screen_status = StoreInfoParser.instance().getScreenSaver()
    if(screen_status == "enable"):
        os.system("xset s on")
        os.system("xset +dpms")
    elif(screen_status == "disable"):
        os.system("xset s off")
        os.system("xset -dpms")
    else:
        s = "disable"
        StoreInfoParser.instance().setScreenSaver(s)
        os.system("xset s off")
        os.system("xset -dpms")
        
def getCmdOut(command):
    """
    获得命令的输出内容
    """
    output = None
    statusOutput = commands.getstatusoutput(command)
    if statusOutput[0] == 0:#如果是0，则执行成功
        output = statusOutput[1]#第二个元素就是命令行执行后的输出
        return output.split("\n")
    
    return output

def checkUsbIsAutoConnect():
    return StoreInfoParser.instance().getUsbIsAutoConnect()
    
    
def getActiveMonitors():
    """
    获取显示器列表
    """
    monitorList = []
    temp = getCmdOut("xrandr |awk '/connected/'")
    for i in range(len(temp)):
        if(temp[i].split(" ")[1] == "connected"):
            monitorList.append(temp[i].split(" ")[0]);
    return monitorList
    
def isMultiConnect():
    value = StoreInfoParser.instance().getMultiConnectState()
    if (value == None):
        return False,""

    if (value.split(":")[1] == "disable" or value.split(":")[1] == "None"):
        return False,""

    resolution = value.split(":")[1]
    return True,resolution
    
def setResolution():
    """
    设置系统的分辨率
    """
    #获得显示器名称，连接状态及行号
    aMonitors = getCmdOut("xrandr | awk '{ if($2 ~ \"connected\") {print $1 \" \" $2 \" \" NR}}'")
    if aMonitors is None:
        return

    #根据组合列表把显示器名称和支持的分辨率放入到一个字典中
    resolutionMap = {}
    Monitors = []
    #获得显示平名字列表
    for j in range(len(aMonitors)):
        if len(aMonitors[j].split(" ")) == 3:
            Monitors.append(aMonitors[j])

    count = len(Monitors)
    for i in range(count):
        rowStopNumber = ""
        monitorName = Monitors[i].split(" ")[0]
        linkStatus = Monitors[i].split(" ")[1]
        rowStartNumber = Monitors[i].split(" ")[2]
        if (linkStatus == "disconnected"):
            continue
        if (i != count - 1):
            rowStopNumber = Monitors[i+1].split(" ")[2];

        if (rowStopNumber == ""):
            resolutionCmd = "xrandr | awk '{ if(NR > " + rowStartNumber + ")" + "{print $1}}'"
        else:
            resolutionCmd = "xrandr | awk '{ if((NR > " + rowStartNumber + ") && (NR < " + rowStopNumber + "))" + "{print $1}}'"

        resolutionList = getCmdOut(resolutionCmd)
        if resolutionList is None:
            break
        
        if len(resolutionList[0].split(" ")) >4:
            resolutionList.remove(resolutionList[0])
        resolutionMap[monitorName] = resolutionList
        
    currentSolution = StoreInfoParser.instance().getScreen()
    if currentSolution:
        for key in resolutionMap:
            name = key
            screenName = currentSolution.split(":")[0]
            resolution = currentSolution.split(":")[1]
            if (screenName == name):
                reList = resolutionMap[key]
                if (QStringList(reList).contains(resolution)):
                    cmd = QString("xrandr ") + " --output " + screenName + " --mode " + resolution
                    os.system(str(cmd))
                    return
                
#         cmd = QString("xrandr ") + " --output " + name + " --mode " + "1024x768"
#         os.system(str(cmd))
#         reContent = name + ":" + "1024x768"
#         StoreInfoParser.instance().setScreen(reContent)
#     else:
    for key in resolutionMap:
        screenName = key
        cmd = QString("xrandr ") + " --output " + screenName + " --mode " + "1024x768"
        ok = os.system(str(cmd))
        if (ok == 0):
            reContent = screenName + ":" + "1024x768"
            StoreInfoParser.instance().setScreen(reContent) 


        
def configNetEthFile():
    """
    配置网卡文件
    """
    if QFile.exists("/etc/sysconfig/network-scripts/ifcfg-breth0"): 
        return
    
    os.system("touch /etc/sysconfig/network-scripts/ifcfg-breth0")
    os.system("echo 'DEVICE=breth0' > /etc/sysconfig/network-scripts/ifcfg-breth0")
    os.system("echo 'TYPE=Bridge' >> /etc/sysconfig/network-scripts/ifcfg-breth0")
    os.system("echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0")
    os.system("echo 'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/ifcfg-breth0")
    
    netcardInfo = commands.getstatusoutput("ls /sys/class/net")
    if netcardInfo[0] != 0:
        return
    
    netcardList = "".join(netcardInfo[1]).split("\n")
    validNetCardList = [netcard for netcard in netcardList if netcard not in ["br0", "lo", "breth0", "virbr0-nic", "virbr0"]]
    
    for netcard in validNetCardList:
        os.system("touch /etc/sysconfig/network-scripts/ifcfg-%s" % netcard)
        os.system("echo 'DEVICE=%s' > /etc/sysconfig/network-scripts/ifcfg-%s" % (netcard, netcard))
        os.system("echo 'TYPE=Ethernet' >> /etc/sysconfig/network-scripts/ifcfg-%s" % netcard)
        os.system("echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-%s" % netcard)
        os.system("echo 'BRIDGE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-%s" % netcard)
        os.system("echo 'BOOTPROTO=none' >> /etc/sysconfig/network-scripts/ifcfg-%s" % netcard)
    
    if not QFile.exists("/etc/sysconfig/network-scripts/wlan0"):
        os.system("touch /etc/sysconfig/network-scripts/wlan0")
        os.system("echo 'DEVICE=wlan0' > /etc/sysconfig/network-scripts/wlan0")
        os.system("echo 'TYPE=Wireless' >> /etc/sysconfig/network-scripts/wlan0")
        os.system("echo 'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/wlan0")
  
    return
