# -*- coding:utf-8 -*-

import nacos
# import threading
# from nacos.listener import SubscribeListener
from tornado.options import define, options
import yaml
import platform
import string
import redis
from redis.sentinel import Sentinel
from mongoengine.connection import disconnect


# 当前注册的名称
define("appName", default='meduData', help="app name in nacos", type=str)
maxResponseCount = 500


def trim(s):
    import re
    if s.startswith(' ') or s.endswith(' '):
        return re.sub(r"^(\s+)|(\s+)$", "", s)
    return s


def nacos_main(nacosConf):
    global maxResponseCount
    global mongodb_cfg_map, redis_cfg_map, templateFileServerUrlMap
    # print(nacosConf)
    try:
        if nacosConf is None:
            nacos_client = nacos.NacosClient('192.168.1.31:9003', namespace='2288830d-a768-4971-c814-14d227d544d2',
                                             username='nacos', password='nacos')
            nacos_config = nacos_client.get_config('AnalysisProvider.yaml', 'DEFAULT_GROUP', 5000)
        else:
            nacos_client = nacos.NacosClient(getHostIP(nacosConf["nacos_server"]), namespace=nacosConf["nacos_namespace"],
                                             username=nacosConf["nacos_user"], password=nacosConf["nacos_password"])
            nacos_config = nacos_client.get_config(nacosConf['nacos_data_id'], nacosConf['nacos_group'], 5000)
    except Exception as ex:
        nacos_config = None
        print(ex)
    # print(nacos_config)
    nacos_config_dict = yaml.load(nacos_config, Loader=yaml.FullLoader)
    cs_text = nacos_config_dict["spring"]["data"]["mongodbConfig"]
    rs_text = nacos_config_dict["spring"]["redis"]
    if nacos_config_dict["spring"]["data"].get('maxResponseCount') is not None:
        maxResponseCount = nacos_config_dict["spring"]["data"]['maxResponseCount']
    else:
        maxResponseCount = 500
    mongodb_cfg_map, redis_cfg_map, templateFileServerUrlMap = {}, {}, {}
    for i in cs_text:
        if i != "":
            plat = i["plat"]
            if ',' in plat:
                plats = plat.split(',')
            else:
                plats = [plat]
            for plat in plats:
                plat = trim(plat)
                mongodb_cfg, templateUrl = {}, ""
                if str(i["uri"]).find('replicaSet=') > 0:
                    mongodb_cfg["uri"] = str(i["uri"])
                    mongodb_cfg["host"] = ""
                    mongodb_cfg["port"] = "0"
                    mongodb_cfg["db_name"] = ""
                    mongodb_cfg["user"] = ""
                    mongodb_cfg["password"] = ""
                else:
                    cfg_1 = i["uri"]
                    cfg_1 = cfg_1.replace('mongodb://', '')
                    cfg_1 = cfg_1.split("/")
                    cfg_0 = cfg_1[0].split(":")
                    # mongodb_cfg["plat"] = plat
                    mongodb_cfg["host"] = cfg_0[0]
                    mongodb_cfg["port"] = cfg_0[1]
                    mongodb_cfg["db_name"] = cfg_1[1]
                    # mongodb_cfg["db_name"]=cfg_1[1]
                    if i["user"] is not None or i["user"] != '':
                        mongodb_cfg["user"] = i["user"]
                        mongodb_cfg["password"] = i["password"]
                    else:
                        mongodb_cfg["user"] = ""
                        mongodb_cfg["password"] = ""
                    mongodb_cfg["uri"] = None
                mongodb_cfg_map[plat] = mongodb_cfg
                if i["templateFileServerUrl"] is not None or i["templateFileServerUrl"] != '':
                    if str(i["templateFileServerUrl"]).find('http://') > -1 or \
                            str(i["templateFileServerUrl"]).find('https://') > -1:
                        templateUrl = i["templateFileServerUrl"]
                    else:
                        templateUrl = 'https://' + plat + str(i["templateFileServerUrl"])
                templateFileServerUrlMap[plat] = templateUrl
    redis_cfg_map["host"] = rs_text["host"]
    redis_cfg_map["password"] = rs_text["password"]
    redis_cfg_map["port"] = rs_text["port"]
    redis_cfg_map["namespace"] = rs_text["namespace"]
    if 'mymaster' in rs_text.keys():
        redis_cfg_map["mymaster"] = rs_text["mymaster"]
    else:
        redis_cfg_map["mymaster"] = 'mymaster'
    redis_connect = get_redis_connect(redis_cfg_map)
    redis_cfg_map['redis_connect'] = redis_connect


def nacos_py(serverUrl):
    global mongodb_cfg_map, redis_cfg_map
    if serverUrl in mongodb_cfg_map:
        mongodb_cfg, template_url = mongodb_cfg_map[serverUrl], templateFileServerUrlMap[serverUrl]
    else:
        if 'default' in mongodb_cfg_map:
            mongodb_cfg, template_url = mongodb_cfg_map['default'], templateFileServerUrlMap['default']
        else:
            mongodb_cfg, template_url = '', ''
    #disconnect(alias='default')
    return mongodb_cfg, maxResponseCount, template_url, redis_cfg_map


def getHostIP(hostName):
    hostNameReturn = hostName
    hostNameAll = str(hostName).split(':')
    if platform.system() == 'Windows':
        HOSTS_PATH = r'C:\WINDOWS\system32\drivers\etc\HOSTS'
    else:
        HOSTS_PATH = r'/etc/hosts'
    with open(HOSTS_PATH, 'r') as f:
        hostlines = f.readlines()
    hostlines = [line.strip() for line in hostlines
                 if not line.startswith('#') and line.strip() != '']
    hosts = []
    for line in hostlines:
        if len(line.split('#')[0].split()) > 1:
            hostips = line.split('#')[0].split()[0]
            hostnames = line.split('#')[0].split()[1]
            hosts.append({hostnames:hostips})
    for hostItem in hosts:
        if hostNameAll[0] in hostItem.keys():
            hostNameReturn = hostItem[hostNameAll[0]] + ':' + hostNameAll[1]
    return hostNameReturn


def get_redis_connect(redis_cfg):
        master = None
        try:
            if str(redis_cfg['host']).find(',') > -1:
                host_list = str(redis_cfg['host']).split(',')
                port_list = str(redis_cfg['port']).split(',')
                host_port_list = []
                for host_list_index, host_list_item in enumerate(host_list):
                    if host_list_index < len(port_list):
                        host_port_list.append((host_list_item, int(port_list[host_list_index])))
                    else:
                        host_port_list.append((host_list_item, int(port_list[0])))
                sentinel = Sentinel(host_port_list)
                master = sentinel.master_for(redis_cfg['mymaster'], socket_timeout=1000, password=redis_cfg['password'],
                                             decode_responses=False)
            else:
                master = redis.Redis(host=redis_cfg['host'], port=redis_cfg['port'], password=redis_cfg['password'],
                                     decode_responses=False)
        except Exception as ex:
            print(ex)
        finally:
            return master