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

#import usb


import commands
import os
import socket
import struct
import uuid

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

from base.storeinfoparser import StoreInfoParser
import fcntl


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]

def get_Eth_Name():
    """create for pbc on 2015.8.5"""
    try:
        netcardList = "".join(commands.getstatusoutput("ls /sys/class/net")[1]).split("\n")
        validNetCardList = [netcard for netcard in netcardList if netcard not in ["br0", "lo", "breth0", "virbr0-nic", "virbr0"]]
        if len(validNetCardList)>0:
            return validNetCardList[0]
        else:
            return "enp2s0"
    except:
        return "enp2s0"


#得到本机的IP地址
def get_ip_address():
    """create by pbc for get ipaddress method    2015.8.5 """
    try:
        ipaddr = socket.gethostbyname(socket.gethostname())
        if ipaddr != "127.0.0.1":
            return ipaddr
        else:
            try:
                ifname = get_Eth_Name()
                if ifname == "":
                    return "0.0.0.0"
                s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                ipd= socket.inet_ntoa(fcntl.ioctl(s.fileno(),
                                                  0X8915,
                                                  struct.pack('256s',ifname[:15]))[20:24])
                return ipd
            except:
                return "0.0.0.0"
    except:
        return "0.0.0.0"



#获取本机网关
def get_netmask_gateway_dns():
    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 = 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
    
    
    
