# Create your views here.

import json

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

import polynum.base.models as models

def entity2json(entity):
    return dict(
            id=entity.id,
            code=entity.code,
            name=entity.get_name().strip().title(),
            description=entity.get_description(),
            is_leaf=entity.right_bound == entity.left_bound + 1,
            parent_id=entity.parent_id,
            type=entity.entity_type.name,
    )

def entity_parents(request, code=None):
    entity = models.Entity.objects.get(id=code)
    return HttpResponse(json.dumps(list([e.id for e in entity.parents(True)])))

def entity(request, code=None):
    _filter = request.GET.get('filter')
    res = {}
    if code:
        entity = models.Entity.objects.select_related('entity_type', 'parent').get(id=code)
        res = entity2json(entity)
        child_qs = entity.children().filter(depth=entity.depth+1, is_active=True).select_related('parent')
    else:
        res = dict(id=None, code=None, name=None, description=None, is_leaf=False)
        child_qs = models.Entity.objects.filter(depth=1, is_active=True).select_related('parent')
    child_qs = child_qs.select_related('entity_type')
    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))
    child_qs = child_qs.order_by('description', 'name')
    res['children'] = [ entity2json(e) for e in child_qs ]
    return HttpResponse(json.dumps(res))
