"""
.. module:: elasticsearch
   :synopsis: Elasticsearch protocol module

.. moduleauthor:: <NAME> <<EMAIL>>
"""

import time
import uuid
import json
from base64 import b64encode

from duct import utils

class ElasticSearch(object):
    """Twisted ElasticSearch API
    """
    def __init__(self, url='http://localhost:9200', user=None, password=<PASSWORD>,
                 index='duct-%Y.%m.%d'):
        self.url = url.rstrip('/')
        self.index = index
        self.user = user
        self.password = password

    def _get_index(self):
        return time.strftime(self.index)

    def _request(self, path, data=None, method='GET'):
        headers = {}
        if self.user:
            authorization = b64encode('%s:%s' % (self.user, self.password)
                                     ).decode()
            headers['Authorization'] = ['Basic ' + authorization]

        return utils.HTTPRequest().getJson(
            self.url + path, method, headers=headers, data=data.encode())

    def _gen_id(self):
        return b64encode(uuid.uuid4().bytes).decode().rstrip('=')

    def stats(self):
        """Return statistics for the cluster
        """
        return self._request('/_cluster/stats')

    def node_stats(self):
        """Return statistics for this node
        """
        return self._request('/_nodes/stats')

    def insertIndex(self, index_type, data):
        """Insert an index
        """
        return self._request('/%s/%s/%s' % (self._get_index(), index_type,
                                            self._gen_id()),
                             json.dumps(data), 'PUT')

    def bulkIndex(self, data):
        """Insert many indicies
        """
        serdata = ""

        for row in data:
            if '_id' in row:
                iid = row['id']
                row.pop('id')
            else:
                iid = self._gen_id()

            data = {
                "index": {
                    "_index": self._get_index(),
                    "_type": row.get('type', 'event'),
                    "_id": iid,
                }
            }

            serdata += json.dumps(data) + '\n'
            serdata += json.dumps(row) + '\n'

        return self._request('/_bulk', serdata, 'PUT')

"""
.. module:: elasticsearch
   :synopsis: Elasticsearch protocol module

.. moduleauthor:: <NAME> <<EMAIL>>
"""

import time
import uuid
import json
from base64 import b64encode

from duct import utils

class ElasticSearch(object):
    """Twisted ElasticSearch API
    """
    def __init__(self, url='http://localhost:9200', user=None, password=<PASSWORD>,
                 index='duct-%Y.%m.%d'):
        self.url = url.rstrip('/')
        self.index = index
        self.user = user
        self.password = password

    def _get_index(self):
        return time.strftime(self.index)

    def _request(self, path, data=None, method='GET'):
        headers = {}
        if self.user:
            authorization = b64encode('%s:%s' % (self.user, self.password)
                                     ).decode()
            headers['Authorization'] = ['Basic ' + authorization]

        return utils.HTTPRequest().getJson(
            self.url + path, method, headers=headers, data=data.encode())

    def _gen_id(self):
        return b64encode(uuid.uuid4().bytes).decode().rstrip('=')

    def stats(self):
        """Return statistics for the cluster
        """
        return self._request('/_cluster/stats')

    def node_stats(self):
        """Return statistics for this node
        """
        return self._request('/_nodes/stats')

    def insertIndex(self, index_type, data):
        """Insert an index
        """
        return self._request('/%s/%s/%s' % (self._get_index(), index_type,
                                            self._gen_id()),
                             json.dumps(data), 'PUT')

    def bulkIndex(self, data):
        """Insert many indicies
        """
        serdata = ""

        for row in data:
            if '_id' in row:
                iid = row['id']
                row.pop('id')
            else:
                iid = self._gen_id()

            data = {
                "index": {
                    "_index": self._get_index(),
                    "_type": row.get('type', 'event'),
                    "_id": iid,
                }
            }

            serdata += json.dumps(data) + '\n'
            serdata += json.dumps(row) + '\n'

        return self._request('/_bulk', serdata, 'PUT')

.. module:: elasticsearch    :synopsis: Elasticsearch protocol module  .. moduleauthor:: <NAME> <<EMAIL>> Twisted ElasticSearch API Return statistics for the cluster Return statistics for this node Insert an index Insert many indicies