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

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


class CenterName(object):

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

    def getCenterName(self): # 获取session信息
        '''
            seccess : return [ True,   "centerName" ]
            filed   : return [ False,  "filed info"]
        '''
        try:
            url = "%s/api/terminals/checkCenterName"% self.__url

            LogRecord.instance().logger.info("url : " + url)
            recv = requests.get(url,timeout=4)
            recv.raise_for_status()    # 如果响应状态码不是 200，就主动抛出异常

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

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

            if dict_tmp == None:
                raise Exception("getCenterNam result == None")

            status = dict_tmp["status"]

            # import chardet
            # print "编码",chardet.detect(str(status))

            info   = str(dict_tmp["info"].encode('utf-8'))

            if status != "y":
                LogRecord.instance().logger.error("GetCenterName : " + info)
                # print "info : %s " % info
                return False,str(info)

            name = dict_tmp["centerName"]
            return True, name

        except requests.exceptions.ConnectionError as e:
            LogRecord.instance().logger.exception("获取平台名称,网络连接错误")
            return False,"添加平台,网络异常或平台地址验证失败"

        except requests.exceptions.Timeout as e:
            LogRecord.instance().logger.exception("获取平台名称,网络超时")
            return False,"添加平台,网络超时"

        except Exception as e:
            LogRecord.instance().logger.exception("GetCenterName")
            return False, "获取平台名称异常,请检查网络是否正常"

if __name__ == "__main__":
    from os import getenv,environ
    if getenv('LOG_STDOUT') == None:
        environ["LOG_STDOUT"] = "stdout"  #

    centerName = CenterName("192.168.8.5:8080")
    flag,name = centerName.getCenterName()
    print flag, name
    print type(name)
    print type("")
    print type(name) == type("")

