# coding: utf-8
# © 2015 Instacart
from collections import defaultdict
from datetime import datetime
import json

import docker

from .version import version
from .logger import log


class Ahab(object):
    def __init__(self, url='unix:///var/run/docker.sock', handlers=[]):
        self.url = url
        self.handlers = handlers if len(handlers) > 0 else [Ahab.default]
        self.data = defaultdict(dict)

    def listen(self):
        client = docker.Client(base_url=self.url)
        for event in client.events(decode=True):
            if 'time' in event:
                event['time'] = datetime.fromtimestamp(event['time'])
            log.debug('Event: %s', event)
            try:
                if 'from' in event:
                    data = client.inspect_container(event['id'])
                else:
                    data = client.inspect_image(event['id'])
                self.data[event['id']] = data
            except docker.errors.NotFound:
                data = self.data[event['id']]
            self.handle(event, data)

    def handle(self, event, data):
        for handler in self.handlers:
            handler(event, self.data[event['id']])

    @staticmethod
    def default(event, data):
        """The default handler prints basic event info."""
        messages = defaultdict(lambda: 'Avast:')
        messages['start'] = 'Thar she blows!'
        messages['tag'] = 'Thar she blows!'
        messages['stop'] = 'Away into the depths:'
        messages['destroy'] = 'Away into the depths:'
        messages['delete'] = 'Away into the depths:'
        message = messages[event['status']] + ' %s/%s'
        log.info(message, event['status'], event['id'])
        log.debug('"data": %s', form_json(data))


def form_json(data):
    return json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))


__version__ = version()

@@ -542,17 +542,55 @@
     
-if 'time'
+for k in %5B'time', 'Time'%5D:%0A                if k
  in 
@@ -588,32 +588,36 @@
  if k in event:%0A
+    
                 
@@ -622,22 +622,17 @@
   event%5B
-'time'
+k
 %5D = date
@@ -656,22 +656,17 @@
 p(event%5B
-'time'
+k
 %5D)%0A     
@@ -702,16 +702,102 @@
  event)%0A
+            data = %7B%7D%0A            i = get_id(event)%0A            if i is not None:%0A    
         
@@ -821,16 +821,20 @@
         
+ 
+   
 if 'from
@@ -835,34 +835,57 @@
  'from' in event
-:%0A
+ or 'From' in event:%0A    
                 
@@ -920,29 +920,23 @@
 ntainer(
-event%5B'id'%5D)%0A
+i)%0A    
         
@@ -949,16 +949,20 @@
   else:%0A
+    
         
@@ -1001,29 +1001,23 @@
 t_image(
-event%5B'id'%5D)%0A
+i)%0A    
         
@@ -1034,27 +1034,17 @@
 lf.data%5B
-event%5B'id'%5D
+i
 %5D = data
@@ -1044,16 +1044,20 @@
  = data%0A
+    
         
@@ -1103,24 +1103,28 @@
             
+    
 data = self.
@@ -1128,27 +1128,17 @@
 lf.data%5B
-event%5B'id'%5D
+i
 %5D%0A      
@@ -1273,30 +1273,12 @@
 nt, 
-self.data%5Bevent%5B'id'%5D%5D
+data
 )%0A%0A 
@@ -1672,32 +1672,67 @@
 to the depths:'%0A
+        status = get_status(event)%0A
         message 
@@ -1742,31 +1742,22 @@
 essages%5B
-event%5B'
 status
-'%5D
 %5D + ' %25s
@@ -1791,36 +1791,29 @@
 ge, 
-event%5B'status'%5D, event%5B'id'%5D
+status, get_id(event)
 )%0A  
@@ -1962,16 +1962,232 @@
 : '))%0A%0A%0A
+def get_status(event):%0A    for k in %5B'status', 'Status'%5D:%0A        if k in event:%0A            return event%5Bk%5D%0A%0A%0Adef get_id(event):%0A    for k in %5B'id', 'ID', 'Id'%5D:%0A        if k in event:%0A            return event%5Bk%5D%0A%0A%0A
 __versio

Fix for Docker 1.10