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

from PyQt4.QtCore import QObject
from model.infomodel.vminfo import VmBaseInfo
from model.infomodel.flavorsinfo import FlavorsInfo
        
class HttpRequestsInfoParser(QObject):
    _instance = 0
    def __init__(self):
        super(HttpRequestsInfoParser,self).__init__()
    
        
    @classmethod
    def vmJsonDataParser(cls, infoList):
        """
        解析json格式的虚拟机列表数据
        """
        if not infoList:
            return []
        
        
        vmInfoList = []
        for vmJsonData, flavorsJsonData, imagesJsonData, tenantName, tenantId in infoList:
            for subVMData in vmJsonData.get("servers", []):
                imageId = subVMData["image"]["id"]
                flavorId = subVMData["flavor"]["id"]
                vmBaseInfo = VmBaseInfo()
                vmBaseInfo.id = subVMData["id"]
                vmBaseInfo.chostName = subVMData["name"]
                vmBaseInfo.status = subVMData["status"]
                vmBaseInfo.projectName = tenantName
                vmBaseInfo.tenantId = tenantId
                vmBaseInfo.flavorId = flavorId
                
                imageNameList = [subImageData["name"] for subImageData in imagesJsonData["images"] \
                                                                    if imageId == subImageData["id"]]
                flavorNameList = [[subFlavorData["name"], subFlavorData["ram"], subFlavorData["vcpus"], subFlavorData["disk"]] \
                                    for subFlavorData in flavorsJsonData["flavors"] \
                                                                    if flavorId == subFlavorData["id"]]
                vmBaseInfo.imageName = imageNameList[0] if imageNameList else ""
                vmBaseInfo.configName = flavorNameList[0][0] if flavorNameList else ""
                vmBaseInfo.ram = flavorNameList[0][1] if flavorNameList else ""
                vmBaseInfo.vcpus = flavorNameList[0][2] if flavorNameList else ""
                vmBaseInfo.disk = flavorNameList[0][3] if flavorNameList else ""
                
                vmInfoList.append(vmBaseInfo)
            
        return vmInfoList
        
    @classmethod
    def flavorJsonDataParser(cls, flavorInfo):
        """
        解析json格式的flavors数据
        """
        if not flavorInfo:
            return []
        
        flavorObj = FlavorsInfo()
        if "flavor" in flavorInfo:
            flavorObj.ram = flavorInfo["flavor"].get("ram", "")
            flavorObj.disk = flavorInfo["flavor"].get("disk", "")
            flavorObj.vcpus = flavorInfo["flavor"].get("vcpus", "")
            
        return flavorObj
            
            
        
        
        
        
        