# Create your views here.

import json

from django.http import HttpResponse
from django.db.models import Q

import polynum.base.models as models

def entity(request, code=None):
    _filter = request.GET.get('filter')
    if code:
        entity = models.Entity.objects.get(id=code)
        id = entity.id
        name = entity.name
        description = entity.description
        child_qs = entity.children().filter(depth=entity.depth+1)
        parent_qs = entity.parents().filter(depth=entity.depth-1)
        parent_code = parent_qs[0].code if parent_qs else None
    else:
        id = None
        code = None
        name = None
        description = None
        child_qs = models.Entity.objects.filter(depth=0, is_active=True)
        parent_code = None
    if _filter:
        children = models.Entity.objects.filter(Q(code__icontains=_filter)|Q(description__icontains=_filter)
                |Q(description_override__icontains=_filter)|Q(name_override__icontains=_filter))
        filters = [Q(left_bound__lte=child.left_bound, right_bound__gte=child.right_bound) for child in children]
        child_qs = child_qs.filter(reduce(Q.__or__, filters))
    l = [ { 'id': e.id, 'code': e.code, 'description': e.get_description() } for e in child_qs ]
    return HttpResponse(json.dumps({'parent_code': parent_code,
        'id': id,
        'code': code,
        'name': name.strip(), 
        'description': description.strip(),
        'children': l}))
