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

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


class SpiceDomain(object):

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

        self.__vmlist = None

    #--------------------------------------------------------
    # 功能  ：  获取域名
    #
    #--------------------------------------------------------
    def getSpiceDomain(self):

        if self.__vmInfo["hostId"] == None:
            msg = "%s 虚拟机hostId为空,不可用" % str(self.__vmInfo["vmId"])
            LogRecord.instance().logger.info(msg)
            return False,msg

        url = "%s/api/vitualMachine/vms/%s/%s" % (self.__url,self.__vmInfo["vmId"],self.__vmInfo["hostId"])#
        # url = "http://192.168.102.33:8080/api/vitualMachine/vms/d36d1c2a-21b7-40f9-8415-7529aaeb47da/bd5a4afe-d440-477f-afd1-33b95d55daa0"
        LogRecord.instance().logger.info("getSpiceDomain : %s " % str(url))
        recv = None
        try:
            recv = requests.get(url,timeout=3)

            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"]
            status  = dict_tmp["status"]
            info    = dict_tmp["info"]

            if dict_tmp == None:
                LogRecord.instance().logger.error("获取虚拟机server域异常：None")
                return False , "获取虚拟机server域异常：None"
            if status != "y":
                LogRecord.instance().logger.warn(info)
                return False,info

            try:
                result =  dict_tmp["result"]
                for key in result.keys():
                    if key == "address":
                        tmp =  " %s : %s \n" % (key,result[key])
                        LogRecord.instance().logger.info(tmp + "\n")

                return True, result["address"]      # 返回 域名

            except Exception as e:
                raise e

        except requests.exceptions.ConnectionError as e:
            LogRecord.instance().logger.error("获取虚拟机server域异常 : " +  e.message)
            return False, "获取虚拟机server域异常: http_code %s " % recv.status_code
        except Exception as e:
            LogRecord.instance().logger.exception("获取虚拟机server域异常 ")
            return False,"获取虚拟机server域异常常"

    #--------------------------------------------------------
    # 功能  ：  获取sever ip
    #--------------------------------------------------------
    #
    #   GET
    #   http://192.168.102.33:8080/api/vitualMachine/vms/{vmId}/{hostId}/nics
    #
    #   返回：
    #     {
    #         "result"  : {
    #             "status" : "y"
    #             "info"   : ""
    #             "result" : {
    #                 "hostNics" [
    #                     {
    #                         "name"    :"enp3s0"  ,
    #                         "bridged" : "true",
    #                         "status"  :  {'state' : 'up',  ...}  ,
    #                         "ip"      :{  'setGateway'  : True,
    #                                       'netmask'     : '255.255.255.0',
    #                                       'address'     : '192.168.102.27',
    #                                       'setAddress'  : True,
    #                                       'gateway'     : '192.168.102.254',
    #                                       'setNetmask'  : True }
    #                     }
    #                       ......
    #                       ......
    #                     {
    #                         "name"    :"enp3s0"  ,
    #                         "bridged" : "true",
    #                          "status" :  {'state' : 'down',...}  ,
    #                          "ip" :{'setGateway'  : False,
    #                                 'netmask'     : '',
    #                                 'address'     : '',
    #                                 'setAddress'  : True,
    #                                 'gateway'     : '',
    #                                 'setNetmask'  : True}
    #                     }
    #                   ]
    #
    #             }
    #         }
    #--------------------------------------------------------
    def getSpiceServerIp(self):

        if self.__vmInfo["hostId"] == None:
            msg = "%s 虚拟机hostId为空,不可用" % str(self.__vmInfo["vmId"])
            LogRecord.instance().logger.info(msg)
            return False,msg

        url = "%s/api/vitualMachine/vms/%s/%s/nics" % (self.__url,self.__vmInfo["vmId"],self.__vmInfo["hostId"])#
        LogRecord.instance().logger.info("getSpiceServerIp : %s " % url)
        recv = None
        try:
            recv = requests.get(url,timeout=3)

            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"]
            status  = dict_tmp["status"]
            # info    = dict_tmp["info"]
            info    = str(dict_tmp["info"].encode('utf-8'))

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

            # --------------------  解析 --------------------------------

            serverNetWorkInfoList = []
            try:
                result =  dict_tmp["result"]
                for key in result.keys():
                    if key == "hostNics":
                        hostNics = result[key]

                        for i in range(len(hostNics)):  # 遍历列表
                            serverNetWorkInfo = {
                                "name"    : "",
                                'address' : "",
                                "state"   : "down",
                                "bridged" : "False"
                            }

                            for key in hostNics[i].keys():
                                if key == "name":
                                    serverNetWorkInfo["name"] = hostNics[i][key]
                                    # tmp =  " %s : %s \n" % (key,hostNics[i][key])
                                    # LogRecord.instance().logger.debug(tmp + "\n")
                                if key == "status":
                                    status = hostNics[i][key]
                                    for key in status.keys():
                                        if key == "state":
                                            serverNetWorkInfo["state"] = status[key]
                                            # tmp =  " %s : %s \n" % (key,status[key])
                                            # LogRecord.instance().logger.debug(tmp + "\n")
                                if key == "ip":
                                    ip = hostNics[i][key]
                                    for key in ip.keys():
                                        if key == "address":
                                            serverNetWorkInfo["address"] = ip[key]
                                            # tmp =  " %s : %s \n" % (key,ip[key])
                                            # LogRecord.instance().logger.debug(tmp + "\n")
                                if key == "bridged":
                                    serverNetWorkInfo["bridged"] = hostNics[i][key]
                                    # tmp =  " %s : %s \n" % (key,hostNics[i][key])
                                    # LogRecord.instance().logger.debug(tmp + "\n")

                            serverNetWorkInfoList.append(serverNetWorkInfo)

                            # print "------ ----------- ------- ---------- ----- ---- "
                #print serverNetWorkInfoList

                res = [False,"没有可用的ip"]
                for i in range(len(serverNetWorkInfoList)):
                    if serverNetWorkInfoList[i]["bridged"] == True and \
                        serverNetWorkInfoList[i]["state"] == 'up':

                        res[0] = True
                        res[1] = serverNetWorkInfoList[i]["address"]

                return res     # 返回 域名

            except Exception as e:
                raise e

        except requests.exceptions.ConnectionError as e:
            LogRecord.instance().logger.error("获取虚拟机server Ip 异常 : " +  e.message)
            return False, "获取虚拟机server Ip 异常: http_code %s " % recv.status_code
        except Exception as e:
            LogRecord.instance().logger.exception("获取虚拟机server Ip 异常")
            return False,"获取虚拟机server Ip 异常常"

    #######################################################################################
    # def __print_list(self,tmp_list):
    #     print ""
    #     print "--------------------------"
    #     for i in range(len(tmp_list)):
    #         print "   ",tmp_list[i]
    #
    #     print ""
    #     print "--------------------------"
    #
    # def __print_dict(self,tmp_tict):
    #     print ""
    #     print "--------------------------"
    #     for key in tmp_tict.keys():
    #
    #         if key == "name":
    #             tmp =  " %s : %s \n" % (key,tmp_tict[key])
    #             # print tmp
    #             LogRecord.instance().logger.debug(tmp + "\n")
    #         if key == "status":
    #             tmp =  " %s : %s \n" % (key,tmp_tict[key])
    #             LogRecord.instance().logger.debug(tmp + "\n")
    #         if key == "ip":
    #             tmp =  " %s : %s \n" % (key,tmp_tict[key])
    #             LogRecord.instance().logger.debug(tmp + "\n")
    #         if key == "bridged":
    #             tmp =  " %s : %s \n" % (key,tmp_tict[key])
    #             LogRecord.instance().logger.debug(tmp + "\n")
    #
    #     print ""
    #     print "--------------------------"