# -*- coding: utf-8 -*-  

import uuid

import os
import commands

from PyQt4.QtCore import QString,QPoint,QFile, QFileInfo
from PyQt4.QtGui import QApplication

from model.cfg.storeinfoparser import StoreInfoParser


"""
def isNetUsb():  #获取usb设备的类
    #struct libusb_device **devs
    #struct libusb_device *dev
    #struct libusb_config_descriptor *config
    
    devs = usb.Device
    dev = usb.Device
    config = usb.Configuration
    
    #r = libusb_init(NULL)
    r = usb.core.find(None)
    if(r<0):
        return False
    time.sleep(4)
    #cnt = libusb_get_device_list(NULL, &devs);
    cnt = usb.Bus.devices
    if(cnt<0):
        return False

    while((dev = devs[i++]) != NULL)
    {
        libusb_get_active_config_descriptor(dev, &config);
        int iClass = config->interface->altsetting->bInterfaceClass;
        if(2 == iClass)
        {
            libusb_free_device_list(devs, 1);
            libusb_exit(NULL);
            return true;

        }
    }


    libusb_free_device_list(devs, 1);
    libusb_exit(NULL);
    return false;

}
"""

def moveToCenter(width,height):
    desktop = QApplication.desktop()
    screen = StoreInfoParser.instance().getMultiMonitor()
    if screen == "":
        moveWidth = (desktop.width()-width)/2
    elif screen.split(":")[0] == "enable":
        moveWidth = (desktop.width()/2 - width)/2
    else:
        moveWidth = (desktop.width()-width)/2
    moveHeight = (desktop.height() - height)/2
    return QPoint(moveWidth,moveHeight)
  
#得到本机的MAC地址
def get_mac_address(): 
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:] 
    return ":".join([mac[e:e+2] for e in range(0,11,2)])
    
    
#得到网卡的名称
def getEthName():
    mac = get_mac_address()
    ethContent = os.popen('ifconfig | grep -i "%s"'%mac).readlines()
    return ethContent[0][0:4]


#得到本机的IP地址
# def get_ip_address():
#     ifname = getEthName()
#     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#     return socket.inet_ntoa(fcntl.ioctl(
#         s.fileno(),
#         0x8915,  # SIOCGIFADDR
#         struct.pack('256s', ifname[:15])
#     )[20:24])



#获取本机网关
def get_netmask_gateway_dns():
    netmask = gateway = DNS_first = ""
    statusOutput = []
    outputList = []
    netmask = gateway = DNS_first = ""
    statusOutput = commands.getstatusoutput("cat /etc/sysconfig/network-scripts/ifcfg-eth0")
    if statusOutput[0] == 0:
        outputList = QString(statusOutput[1]).split("\n")
        for value in outputList:
            if value.split("=")[0] == "NETMASK":
                netmask = str(value.split("=")[1])
            elif value.split("=")[0] == "GATEWAY":
                gateway = str(value.split("=")[1])
            elif value.split("=")[0] == "DNS1":
                DNS_first = str(value.split("=")[1])
    else:
        netmask = gateway = DNS_first = ""
        
    return [netmask, gateway, DNS_first]

#获取本机网络类型
def get_network_type():
    netType = None
    output = ""
    statusOutput = []
    statusOutput = commands.getstatusoutput("cat /etc/sysconfig/network-scripts/ifcfg-eth0")
    if statusOutput[0] == 0:
        output = QString(statusOutput[1])
        if output.contains("dhcp"):
            netType = "dhcp"
        else:
            netType = "static"
            
    return netType
    

#把课程信息转换为创建虚拟机的参数信息
def lessonInfoConvertToParamInfo(lsInfo):
    paramInfo = {}
    terminalName = StoreInfoParser.instance().getTerminalName()
    paramInfo["configure"] = "standard"
    paramInfo["cpus"] = lsInfo["cpu_cores"]
    paramInfo["memory"] = lsInfo["memory"]
    paramInfo["disk"] = lsInfo["disk"]
    paramInfo["name"] = terminalName + lsInfo["name"]
    paramInfo["os"] = lsInfo["cdrom"].split("/")[-1]
    paramInfo["iso_path"] = lsInfo["cdrom"]
    paramInfo["course_flag"] = '0'
    paramInfo["use_flag"] = True
    return paramInfo
    
#根据虚拟机的名称从虚拟机列表中找到该名称的虚拟机所有信息
def getVMInfoFromVMS(vmsInfoList, name):
    vmInfo = {}
    for subInfo in vmsInfoList:
        if subInfo["name"] == name:
            vmInfo = subInfo
            
    return vmInfo
    
#从云主机广播的信息中根据本机的MAC值来提取分配给该学生机的云桌面名称
def getVMCloudsNameFromBroadInfo(data):
    contentList = data.split("||")
    length = len(contentList)
    mac = get_mac_address()
    vmName = None
    for i in range(length):
        if contentList[i].split(",")[0] == mac:
            vmName = contentList[i].split(",")[1]
            break
        
    return vmName
        
#设置计算机的名称
def setStuentPCName(pcName):
    cmdDelete = "sed -i /HOSTNAME/d /etc/sysconfig/network"
    cmdAppend = "sed -i '$ a\\HOSTNAME=%s' /etc/sysconfig/network" % pcName
    cmd = cmdDelete + "&&" + cmdAppend
    if os.system(cmd) != 0:
        return False
    
    return True
    
    
    
