"""
Log actions to Elastic Search (via UDP)
"""

import datetime as _datetime
import json as _json
import socket as _socket

try:
    from django.conf import settings as _django_settings
except ImportError as e:
    _django_settings = None


DEFAULT = {
    'host': 'localhost',
    'port': 9700,
    'protocol': 'UDP',
    }


if _django_settings and _django_settings.configured:
    for key,value in DEFAULT.items():
        django_key = 'ELASTIC_SEARCH_LOGGING_{}'.format(key.upper())
        DEFAULT[key] = getattr(_django_settings, django_key, value)


### These have dumb names, but we might want them in some form? ###
def log_request(request):
    log(request.user, 'request', body=request.read())

def realy_quick_log(request):
    log(request.user, request.get_full_path())

def quick_log(request, what, **kwargs):
    log(request.user, what, **kwargs)



#-----------------------------------------------------------------------------#
# Real stuff
#-----------------------------------------------------------------------------#
def log(who, what, **kwargs):
    """
    This function combines in arguments, possibly setting an index,
    adds a consistant timestamp and hands it off to ElasticSearch
    """
    payload = {
        'who': who,
        'what': what,
        'when': _datetime.datetime.utcnow().isoformat()
    }

    if 'index' in kwargs.keys():
        index = kwargs['index']
        del kwargs['index']
    else:
        index = 'performance-' + _datetime.date.today().strftime('%Y.%m.%d')

    for key, value in kwargs.iteritems():
        payload[key] = value

    emit(index, payload)

def emit(index, payload, host=None, port=None, protocol=None):
    """
    This function send data to ElasticSearch
    """
    #TODO indexes, types, and what Kibana likes.
    #Try it out and adjust
    #throwing all of payloads **kwargs into an 'additional' or simular field might 
    #required, and I don't know what happens if we send different data types with
    #the same name ie a **kwargs of my_special_key: str and my_special_key: {'foo': 'bar'}
    if host is None:
        host = DEFAULT['host']
    if port is None:
        port = DEFAULT['port']
    if protocol is None:
        protocol = DEFAULT['protocol']
    if protocol == 'UDP':
        socket_type = _socket.SOCK_DGRAM
    else:
        raise NotImplementedError(protocol)

    index_json_str = """{ "index": {"_index": "%s", "_type": "%s"} }""" %(index, "record")
    message =  "%s\n%s\n" % (index_json_str, _json.dumps(payload))
    print message
    sock = _socket.socket(_socket.AF_INET, socket_type)
    sock.sendto(message,(host, port))
    sock.close()

if __name__ == '__main__':
    for i in range(10):
        log('somebody', 'Did something %sx times' % i)

@@ -313,16 +313,88 @@
  'UDP',%0A
+    'index': 'log',%0A    'datestamp_index': False,%0A    'type': 'record',%0A
     %7D%0A%0A%0A
@@ -1409,189 +1409,8 @@
  %7D%0A%0A
-    if 'index' in kwargs.keys():%0A        index = kwargs%5B'index'%5D%0A        del kwargs%5B'index'%5D%0A    else:%0A        index = 'performance-' + _datetime.date.today().strftime('%25Y.%25m.%25d')%0A%0A
     
@@ -1490,23 +1490,35 @@
 mit(
-index, payload)
+payload=payload, **kwargs)%0A
 %0A%0Ade
@@ -1524,23 +1524,16 @@
 ef emit(
-index, 
 payload,
@@ -1568,16 +1568,70 @@
 col=None
+,%0A         index=None, datestamp_index=None, type=None
 ):%0A    %22
@@ -2198,280 +2198,688 @@
  if 
-protocol == 'UDP':%0A        socket_type = _socket.SOCK_DGRAM%0A    else:%0A        raise NotImplementedError(protocol)%0A%0A    index_json_str = %22%22%22%7B %22
+index is None:%0A        index = DEFAULT%5B'index'%5D%0A    if type is None:%0A        type = DEFAULT%5B'type'%5D%0A    if datestamp_index is None:%0A        datestamp_index = DEFAULT%5B'datestamp_index'%5D%0A    if protocol == 'UDP':%0A        socket_type = _socket.SOCK_DGRAM%0A    else:%0A        raise NotImplementedError(protocol)%0A    if datestamp_index:%0A        index = '-'.join(%5B%0A            index,%0A            _datetime.date.today().strftime('%25Y.%25m.%25d'),%0A            %5D)%0A%0A    index_data = %7B%0A        '
 index
-%22: %7B%22
+': %7B%0A            '
 _index
-%22: %22%25s%22, %22
+': index,%0A            '
 _type
-%22: %22%25s%22%7D %7D%22%22%22 %25(index, %22record%22)%0A    message =  %22%25s%5Cn%25s%5Cn%22 %25 (index_json_str, _json.dumps(payload))
+': type,%0A            %7D,%0A        %7D%0A    message = '%5Cn'.join(%5B%0A        _json.dumps(index_data),%0A        _json.dumps(payload),%0A        '',%0A        %5D)%0A
 %0A   
@@ -3068,16 +3068,20 @@
     log(
+who=
 'somebod
@@ -3084,16 +3084,21 @@
 ebody', 
+what=
 'Did som

Make index, index-datestamping, and type configurable