#!/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 SyncCenterClock(object):

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

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

            LogRecord.instance().logger.info("url : " + url)
            recv = requests.get(url,timeout=3)
            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)
                return False,str(info)

            if not dict_tmp.has_key("result"):
                raise Exception("resutl format err, not have key result ;" )

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

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

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

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

if __name__ == "__main__":

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

    chkCenterTime= SyncCenterClock("192.168.102.33:8080")
    flag,__time = chkCenterTime.checkCenterTime()
    print flag, __time
    print type(__time)
    print type("")
    print type(__time) == type("")


    print "-----------"
    print __time/1000.0
    time_struct = time.gmtime(__time/1000.0 + 8 * 60 * 60) # 北京时间
    __date = "%s-%s-%s %s:%s:%s" % (time_struct.tm_year,time_struct.tm_mon,time_struct.tm_mday,\
                                    time_struct.tm_hour,time_struct.tm_min,time_struct.tm_sec)
    print __date


    time_struct = time.gmtime(__time/1000.0)  # 格林威治时间
    __date = "%s-%s-%s %s:%s:%s" % (time_struct.tm_year,time_struct.tm_mon,time_struct.tm_mday, \
                                    time_struct.tm_hour,time_struct.tm_min,time_struct.tm_sec)
    print __date
