# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import

import traceback, sys

from .data import DataSink
import elasticsearch
from search.utils.es import get_es, es_index_adapt
from django.conf import settings


class EsDataSink(DataSink):

    def __init__(self, es_type):
        self.es = get_es()
        self.es_index_prefix = settings.ES_INDEX_PREFIX
        self.es_type = es_type

    def __setitem__(self, key, value):
        index = es_index_adapt(
            index_prefix=self.es_index_prefix,
            doc_type=self.es_type,
            rw='write'
        )
        self.es.index(
            index=index,
            doc_type=self.es_type,
            id=key,
            body=value,
            timeout=settings.ES_WRITE_TIMEOUT,
        )

    def __delitem__(self, key):
        try:
            index = es_index_adapt(
                index_prefix=self.es_index_prefix,
                doc_type=self.es_type,
                rw='write'
            )
            self.es.delete(
                index=index,
                doc_type=self.es_type,
                id=key,
                timeout=settings.ES_WRITE_TIMEOUT,
            )
        except elasticsearch.TransportError as e:
            sys.stderr.write(traceback.format_exc()+'\n')
