def deep_itemgetter(key):
    items = key.split('__')

    def g(obj):
        for name in items:
            obj = obj[name]
        return obj
    return g


class EventsBinder(object):

    def __init__(self, start_key, end_key):
        self.start_getter = deep_itemgetter(start_key)
        self.end_getter = deep_itemgetter(end_key)
        self.heap = []

    def bind(self, event):
        lower_event = {'level': 0}
        for prev_event in self.heap:
            if self.end_getter(prev_event) > self.start_getter(event):
                lower_event = prev_event
            else:
                break

        self.heap = self.heap[:lower_event['level']]
        self.heap.append(event)
        event['level'] = lower_event['level'] + 1
