import functools
from django.db.models import Q
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
from avocado.models import DataField
from avocado.events import usage
from restlib2.http import codes
from restlib2.resources import Resource
from serrano.resources.field.values import FieldValues
from preserialize.serialize import serialize


def item_posthook(instance, data, request, pk):
    "Post-serialize hook for item instances."
    uri = request.build_absolute_uri

    data.update({
        'label': unicode(instance),
        'value': instance.pk,
    })

    parent_kwargs = {'pk': pk}
    if instance.parent_id:
        parent_kwargs['item_pk'] = instance.parent_id

    # Add link to self and parent
    data['_links'] = {
        'self': {
            'href': uri(reverse('vocab:item', kwargs={
                'pk': pk,
                'item_pk': data['id'],
            }))
        },
        'parent': {
            'href': uri(reverse('vocab:items', kwargs=parent_kwargs))
        }
    }

    # If this item is not a terminal, add link to child nodes
    if not instance.terminal:
        data['_links']['children'] = {
            'href': uri(reverse('vocab:items', kwargs={