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


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 get_es(es_hosts_config=None):
    init_args = {
        # 'hosts':settings.ES_HOSTS,
        # no sniffing
        'sniff_on_start': False,
        'sniff_on_connection_fail': False,
    }
    new_hosts = settings.ES_V2_HOSTS if not es_hosts_config else es_hosts_config
    new_es = Es(hosts=new_hosts, **init_args)
    return new_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],
        'fragment_size': 10000,
        "require_field_match": False
    }
    return field_highlight


def get_highlight_query(fields=[], query=''):
    field_highlight = {
        'fields': {k: {"highlight_query": {
            "bool": {
                "must": {
                    "match": {
                        k: {
                            "query": query
                        }
                    }
                },
                "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,

    }
    return field_highlight


def get_highlight_query_analyzer(fields=[], query=''):
    field_highlight = {
        'fields': {k: {"highlight_query": {
            "bool": {
                "must": {
                    "match": {
                        k: {
                            "query": query
                        }
                    }
                },
                "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,

    }
    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 es_msearch(query_body, es_cli=None, es_hosts_config=None):
    if es_cli is None:
        if es_hosts_config:
            es_cli = get_es(es_hosts_config)
        else:
            es_cli = get_es()

    res = es_cli.msearch(query_body)

    return res


def es_query(sub_index_name, body, offset, size, es=None, doc_type="_doc"):
    if es is None:
        es = get_es()
    index = es_index_adapt(
        index_prefix=settings.ES_INDEX_PREFIX,
        doc_type=sub_index_name,
        rw='read'
    )
    res = es.search(
        index=index,
        # doc_type=doc_type,
        timeout=settings.ES_SEARCH_TIMEOUT,
        body=body,
        from_=offset,
        size=size)
    return res


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_must_query(f):
    q = {
        "query": {
            'bool': {
                'must': f
            }
        }

    }
    return q
