# coding=utf-8
import elasticsearch
from elasticsearch import Elasticsearch as Es
from django.conf import settings
from pytz import timezone


def tzlc(dt, truncate_to_sec=True):
    if dt is None:
        return None
    if truncate_to_sec:
        dt = dt.replace(microsecond=0)
    return timezone(settings.TIME_ZONE).localize(dt)


def es_index_adapt(index_prefix, doc_type, rw=None):
    """get the adapted index name
    """
    assert rw in [None, 'read', 'write']
    index = '-'.join((index_prefix, doc_type))
    if rw:
        index = '-'.join((index, rw))
    return index


def es_multi_index_adapt(index_prefix, doc_type_list, rw=None):
    """get the adapted index name
    """
    indexes = []
    for doc_type in doc_type_list:
        index = es_index_adapt(index_prefix, doc_type, rw=rw)
        indexes.append(index)
    return indexes


def get_es():
    init_args = {
        'sniff_on_start': False,
        'sniff_on_connection_fail': False,
    }
    new_hosts = settings.ES7_HOSTS
    new_es = Es(hosts=new_hosts, http_auth=("elastic", "gengmei!@#"), **init_args)
    return new_es


def es_indices_analyze(doc_type, body, es):
    if es is None:
        es = get_es()

    index = es_index_adapt(
        index_prefix=settings.ES_INDEX_PREFIX,
        doc_type=doc_type,
        rw='read'
    )
    res = es.indices.analyze(index=index, body=body)

    return res


def get_talos_es():
    init_args = {
        'sniff_on_start': False,
        'sniff_on_connection_fail': False,
    }
    talos_hosts = settings.TALOS_ES_HOSTS
    talos_es = Es(hosts=talos_hosts,http_auth=("elastic", "gengmei!@#"), **init_args)
    return talos_es


def get_talos_es6():
    init_args = {
        'sniff_on_start': False,
        'sniff_on_connection_fail': False,
    }
    talos_hosts = settings.ES7_HOSTS
    talos_es = Es(hosts=talos_hosts, http_auth=("elastic", "gengmei!@#"),**init_args)
    return talos_es

def get_talos_es7_service():
    init_args = {
        'sniff_on_start': False,
        'sniff_on_connection_fail': False,
    }
    talos_hosts = settings.TALOS_ES_HOSTS
    talos_es = Es(hosts=talos_hosts, http_auth=("elastic", "gengmei!@#"),**init_args)
    return talos_es


HIGHLIGHT_TAG = 'ems'


def get_highlight(fields=[]):
    field_highlight = {
        'fields': {k: {} for k in fields},
        'pre_tags': ['<%s>' % HIGHLIGHT_TAG],
        'post_tags': ['</%s>' % HIGHLIGHT_TAG],
        "require_field_match": False
    }
    return field_highlight


def get_highlight_query(fields=[], query=''):
    field_highlight = {
        'fields': {k: {"highlight_query": {
            "bool": {
                "should": {
                    "match_phrase": {
                        k: {
                            "query": query,
                            "analyzer": "keyword"
                        }
                    }
                },
                "minimum_should_match": 0
            }}} for k in fields},
        'fragment_size': 10000,
        'pre_tags': ['<%s>' % HIGHLIGHT_TAG],
        'post_tags': ['</%s>' % HIGHLIGHT_TAG],
        "require_field_match": False,
        "analyzer": "standard"
    }
    return field_highlight


def health():
    res = {
        'status': 'red',
        'available_nodes': [],
    }

    es = get_es()

    cluster_health = es.cluster.health()
    res['status'] = cluster_health['status']
    nodes_info = es.nodes.info()
    available_nodes = nodes_info['nodes']
    for key, node in available_nodes.items():
        res['available_nodes'].append(node.get('ip'))
    return res


def talos_es_health():
    res = {
        'status': 'red',
        'available_nodes': [],
    }

    es = get_talos_es()

    cluster_health = es.cluster.health()
    res['status'] = cluster_health['status']
    nodes_info = es.nodes.info()
    available_nodes = nodes_info['nodes']
    for key, node in available_nodes.items():
        res['available_nodes'].append(node.get('ip'))
    return res
