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

@author: root
'''
import commands
import os
import time

from PyQt4.QtCore import QString, QByteArray, QCryptographicHash
from PyQt4.QtGui import QApplication

from base.configFileParser import ConfigFileParser
from common import commondata
from common.VmDict import VmDict
from setting.logrecord import LogRecord


def getVersionAndReleaseDate():
    """获取版本信息"""
    MAJOR_VERSION = ""
    MINOR_VERSION = ""
    if os.path.exists("/mcos/dvclient/version"):
        try:
            statusOutput = commands.getstatusoutput("cat /mcos/dvclient/version")
            if statusOutput[0] == 0:
                outputList = QString(statusOutput[1]).split("\n")
                MAJOR_VERSION = outputList[0]
                MINOR_VERSION = outputList[1]
        except Exception as e:
            LogRecord.instance().logger.exception(e)
    return MAJOR_VERSION + " " + MINOR_VERSION

def moveWidgetToScreenCenter(widget):
    desktopWidget = QApplication.desktop()
    clientRect = desktopWidget.availableGeometry()
    width = clientRect.width()
    height = clientRect.height()
    widget.move((width - widget.width())/2,  (height - widget.height())/2)

def isDisksALlDownloaded(uuid):
    ret = True
    uuid = str(uuid)
    parse = ConfigFileParser()
    if not parse.has_option(commondata.CFG_DOWNLOADED_VM_UUID, uuid):
        return False

    paths = parse.getValue(commondata.CFG_DOWNLOADED_VM_UUID, uuid)
    diskList = paths.split(';')
    disks = VmDict.instance().getVmDisks(uuid)
    for disk in disks:
        diskPath = commondata.LIBVIRT_IMAGES_PATH + uuid + '/' + disk.id + '/' + disk.image_id
        ret &= diskList.count(diskPath) > 0
    return ret

def getMD5EncryptValue(content):
    password = QString()
    ba = QByteArray()
    md = QCryptographicHash(QCryptographicHash.Md5)
    ba.append(QString(content))
    md.addData(ba)
    bb = md.result()
    password.append(bb.toHex())
    return str(password)

def getCurrentSystemDate():
    """
    得到当前的系统时间
    """
    return time.strftime('%Y-%m-%d-%H:%M:%S',time.localtime(time.time()))

def getCmdOut(command):
    """
    获得命令的输出内容
    """
    output = None
    statusOutput = commands.getstatusoutput(command)
    if statusOutput[0] == 0:#如果是0，则执行成功
        output = statusOutput[1]#第二个元素就是命令行执行后的输出
        return output.split("\n")
    
    return output
    
def changUSB3ToUSB2():
    output = None
    statusOutput = commands.getstatusoutput("lspci -nn | grep xHCI")
    if statusOutput[0] == 0:
        output = statusOutput[1]
        usb3List =  output.split("\n")

        usbIDInfoList = [item[item.rindex('[') + 1:item.rindex(']')] for item in usb3List if '[' in item and ']' in item]
        for usbId in usbIDInfoList:
            os.system("setpci -H1 -d %s d8.l=0" % usbId)
            os.system("setpci -H1 -d %s d0.l=0" % usbId)
