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

import requests
import json
import  os
from os import system,getenv
from logger.logrecord import LogRecord


class AgentInfo(object):

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


        self.__agentInfo = None
        self.__appInfoList = []
        self.__AppIconDir = getenv('MCOS_APP_ICON_PATH') # 读取环境变量 图片路径

        if not os.path.exists(self.__AppIconDir):        # 如果 不存在，则新建目录
            system("mkdir -p " + self.__AppIconDir)

    def getAppIconPath(self):
        return self.__AppIconDir

    def downloadAppIcons(self):  # 下载应用
        for i in range(len(self.__appInfoList)):
            for key in self.__appInfoList[i].keys():
                if key == "appId":
                    self.__downloadAppIcon(self.__appInfoList[i][key])
    # 下载应用图标
    def __downloadAppIcon(self,appId):
        if self.__AppIconDir == None:
            appIconDir = "./"
            cmd = "wget -t 1 -T 3 -O  %s.png  %s/api/getAppIcon/%s" % (appId,self.__url,appId)
        else:
            appIconDir = self.__AppIconDir
            cmd = "wget -t 1 -T 3 -O  %s/%s.png  %s/api/getAppIcon/%s" % (appIconDir,appId,self.__url,appId)

        LogRecord.instance().logger.info("download app icon .... : %s.png" % appId)
        iconPath = "%s/%s.png" % (appIconDir,appId)

        status = 1
        # print iconPath," : ",os.path.exists(iconPath)

        flag = False
        try:
            flag = os.path.exists(iconPath)
        except Exception as e:
            pass

        if False == flag:  # 如果文件不存在则 下载文件
            status = system(cmd)

        if status != 0 :  # 抛 wget下载异常
            LogRecord.instance().logger.error("download app icon failed : %s.png" % appId)
            return False
        else:
            return True

    # -------------------------------------------------------
    #  解  析
    # -------------------------------------------------------
    def __agentInfo_analysis_JSON(self,str_json):

        agentInfo = {   "agentIp"     : "",
                        "agentPort"   : "",
                        "agentDomain" : ""
                     }
        flag = False
        #print str_json["result"]
        dictVms = str_json
        agentInfo["agentIp"]           = dictVms["fqdn"]

        tmp,agentInfo["agentPort"]     = dictVms["internetPort"].split(":",2)
        agentInfo["agentPort"],tmp     = agentInfo["agentPort"].split(";")
        flag,agentInfo["agentDomain"]  = self.__getAgentDomain()

        return flag,agentInfo


    def getAgentInfo(self):
        try:
            url = "%s/api/session/agentInfo"% self.__url

            payload = {
                "displayName":"xxxx",
                "inDomain"   : "false",
                "login"      : self.__userInfo["userName"],
                "password"   : self.__userInfo["userPassword"]
            }

            headers = {'content-type':'application/json'}
            recv =  requests.post(url,data=json.dumps(payload), headers=headers,timeout=10)

            if recv.status_code != 200:
                # print "status_code : ",recv.status_code
                raise Exception("Http error %s" % recv.status_code)

            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                # print recv.text
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])

            dict_tmp = recv.json()["result"]

            if dict_tmp == None:
                LogRecord.instance().logger.error("获取代理信息失败 : 内容为 None")
                return False,"getAgentInfo  result == None"

            status = dict_tmp["status"]     # 状态
            info   = dict_tmp["info"].encode('utf-8')       # 信息

            if status != "y":
                LogRecord.instance().logger.error("获取代理信息失败 : " + info)
                return False, info
            flag,agentInfo = self.__agentInfo_analysis_JSON(dict_tmp["result"])

            if flag:
                agentInfo["agentDomain"] = agentInfo["agentDomain"]+ "\\"  + self.__userInfo["userName"] # 拼接域名
            else:
                agentInfo["agentDomain"] = self.__userInfo["userName"]

            return True,agentInfo
        except Exception as e:
            # LogRecord.instance().logger.error("获取代理信息失败 : " + str(e.message))
            LogRecord.instance().logger.exception("获取代理信息失败")
            return False,"请求代理信息异常"
    # -------------------------------------------------------
    #  解  析
    # -------------------------------------------------------
    def __applit_analysis_JSON(self,str_json):

        if str_json['result']["status"] != "y":

            # print str_json['result']["info"]

            raise Exception(["getAppListErr"])

        applist = []

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

            appInfo = {   "appId"           : "",
                          "appName"         : "",
                          "executablePath"  : "" }

            #print str_json["result"]['result'][i]
            dictVms = str_json["result"]['result'][i]
            appInfo["appId"]           = dictVms["id"]
            appInfo["appName"]         = dictVms["rename"]
            appInfo["executablePath"]  = dictVms["executablePath"]
            # for key in appInfo.keys():
            #     print "%s : %s " % (key, appInfo[key])
            applist.append(appInfo)
        return applist


    #-----------------------------------
    # 功能  ：  获取虚拟机  列表
    #
    #----------------------------------
    
    def getApplist(self):
        if self.__appInfoList != None:
            del self.__appInfoList
        try:
            url = "%s/api/users/listAppsOwnedOnAgent"% self.__url
            payload = {
                "displayName": "xxxx",
                "inDomain"   : "false",
                "login"      : self.__userInfo["userName"],
                "password"   : self.__userInfo["userPassword"]
            }

            headers = {'content-type':'application/json'}
            recv =  requests.post(url,data=json.dumps(payload), headers=headers,timeout=10)

            if recv.status_code != 200:
                # print "status_code : ",recv.status_code
                raise Exception("Http error %s" % recv.status_code)

            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                # print recv.text
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])

            dict_tmp = recv.json()["result"]
            status = dict_tmp["status"]
            info   = dict_tmp["info"].encode('utf-8')

            if status != "y":
                LogRecord.instance().logger.error("获取应用列表失败 : " + info)
                return False,info

            applist =  self.__applit_analysis_JSON(recv.json())

            #--------------------------------
            for i in range(len(applist)):
                __print_info = "\n"
                for key in applist[i].keys():
                    __print_info = __print_info +  (" %s : %s \n" % (key, applist[i][key]))
                LogRecord.instance().logger.debug(__print_info + "\n")
            #--------------------------------

            self.__appInfoList = applist
            return True,applist

        except Exception as e:
            LogRecord.instance().logger.exception("获取应用列表失败")
            return False,"请求 应用列表异常"

    #-----------------------------------
    # 功能  ： 获取动态密码
    #----------------------------------
    
    def __getAgentDomain(self):

        url = "%s/api/session/dninfo/" % self.__url
        try:
            recv = requests.get(url,timeout=10)
            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'])
            if recv.json()["result"] == None:
                raise Exception("getAgentDomainErr")

            dict_tmp = recv.json()["result"]
            status = dict_tmp["status"]
            info   = dict_tmp["info"].encode('utf-8')

            if status != "y":
                raise Exception(info)


            strDomain = str(dict_tmp["result"][0]["configValue"])   #
            str1,str2 =  strDomain.split(",",2)
            tmp, str_www = str1.split("=",2)
            tmp,str_com  = str2.split("=",2)
            domain = str_www + "." + str_com

            isDomain = str(dict_tmp["result"][1]["configValue"])    # 判断 是否在域
            if isDomain == "1":
                return True,domain
            else:
                return False,domain

        except Exception as e:
            LogRecord.instance().logger.exception("获取代理域名 : ")
            raise e

