#!/usr/bin/env python
#coding=utf-8

import requests
import json
from time import sleep
from logger.logrecord import LogRecord


class VmList(object):

    def __init__(self,usrInfo,ip_port,httpStyle="http"):
        self.__userInfo     = usrInfo
        self.__url          = httpStyle + "://" + ip_port

        self.__vmlist = None
    # -------------------------------------------------------
    #  功能 ： 获取 虚拟机 列表 解  析
    # -------------------------------------------------------
    def __vmInfo_analysis(self,result):

        vmInfo = {      "type"     : "",
                        "name"     : "",
                        "vmId"     : "",
                        "osType"   : "",
                        "osStatus" : "",
                        "vmIp"     : None,
                        "vmPort"   : "",
                        "vmPassWd" : "",
                        "vmDomain" : None,
                        "guestAddress" : [],
                        "hostId"   : None
                     }
        dictVms = result
        vmInfo["name"]      = dictVms["name"]
        vmInfo["vmId"]      = dictVms["id"]
        vmInfo["osType"]    = dictVms['os']["type"]
        vmInfo["osStatus"]  = dictVms["status"]["state"]
        if dictVms['display'].has_key("address"):
            vmInfo["type"]      = dictVms['display']["type"]
            # vmInfo["vmIp"]      = dictVms['display']["address"]
            vmInfo["vmPort"]    = dictVms['display']["securePort"]



        if  dictVms['host'] != None:            # 关机状态   dictVms['host'] == None
            if dictVms['host']["id"] != None:
                vmInfo["hostId"] = dictVms['host']["id"]


        if dictVms['guestInfo'] != None: # 虚拟机网卡
            if dictVms['guestInfo']["ips"]  != None:
                if dictVms['guestInfo']["ips"]["ips"]  != None:
                    addresslist = dictVms['guestInfo']["ips"]["ips"]
                    for i in range(len(addresslist)):
                        vmInfo["guestAddress"].append(addresslist[i]["address"])

        #域名
        # if dictVms['display']['certificate'] == None:
        #     vmInfo["vmDomain"] = None
        # else:
        #     vmDomain  = dictVms['display']['certificate']["subject"]
        #     tmp,vmInfo["vmDomain"]  = vmDomain.split("CN=",2)
        # vmInfo["osType"]=  dictVms["os"]["type"]

        return vmInfo
    # -------------------------------------------------------
    #  功能 ： 获取 虚拟机 列表 解  析
    # -------------------------------------------------------
    def __getVMlist_analysis_JSON(self,str_json):
        vmlist = []

        for i in range(len(str_json['result'])):

            # vmInfo = {   "name"     : "",
            #              "vmId"     : "",
            #              "osType"   : "",
            #              "osStatus" : "",
            #              "vmIp"     : "",
            #              "vmPort"   : "",
            #              "vmPassWd" : "",
            #              "vmDomain" : "",
            #              "guestAddress" : []
            #              }
            dictVms = str_json["result"][i]

            vmInfo = self.__vmInfo_analysis(dictVms)
            vmlist.append(vmInfo)
        return vmlist

    #--------------------------------------------------------
    # 功能  ：  获取虚拟机列表
    #
    #--------------------------------------------------------
    def getVMlist(self):
        url = "%s/api/vitualMachine/listByUser/%s" % (self.__url,self.__userInfo["userName"])
        LogRecord.instance().logger.debug(url)
        try:
            recv = requests.get(url,timeout=10)
            LogRecord.instance().logger.debug('recv::'+str(recv))
            recv.raise_for_status()    # 如果响应状态码不是 200，就主动抛出异常
            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                # print recv.headers['content-type']
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])
            #print recv.text
            dict_tmp = recv.json()["result"]
            LogRecord.instance().logger.debug('dict_tmp::')
            status  = dict_tmp["status"]
            # info    = dict_tmp["info"]
            info    = str(dict_tmp["info"].encode('utf-8'))

            if dict_tmp == None:
                LogRecord.instance().logger.debug("获取虚拟机列表异常：None")
                return False , "获取虚拟机列表异常：None"
            if status != "y":
                LogRecord.instance().logger.debug(info)
                return False,info

            vmList = self.__getVMlist_analysis_JSON(dict_tmp)
            LogRecord.instance().logger.debug('vmList::'+str(vmList))
            try:
                ss = "\n"
                for i in range(len(vmList)):
                    ss = ss + "\n"
                    for key in vmList[i].keys():
                        tmp = "%s : %s \n" % (key, vmList[i][key])
                        ss = ss +  tmp

                # LogRecord.instance().logger.debug(ss + "\n")
            except Exception as e:
                LogRecord.instance().logger.exception('parse vmlist exception!')

            if self.__vmlist != None:
                del self.__vmlist

            self.__vmlist = vmList
            LogRecord.instance().logger.debug('get vmlist sucess!')
            return True,vmList

        except requests.exceptions.ConnectionError as e:
            LogRecord.instance().logger.error("getVMlist : %s " % url)
            LogRecord.instance().logger.exception("获取虚拟机列表")
            return False, "获取虚拟机列表,网络连接错误"

        except requests.exceptions.Timeout as e:
            LogRecord.instance().logger.error("getVMlist : %s " % url)
            LogRecord.instance().logger.exception("获取虚拟机列表,网络超时")
            return False,"获取虚拟机列表,网络超时"
        except Exception as e:
            LogRecord.instance().logger.exception("获取虚拟机列表")
            return False,"获取虚拟机列表异常"

