from django.contrib.auth.decorators import login_required
from django.http import JsonResponse


from app.utils.api.api_list import header_for_table
from items.models import Item, ItemRelation, Property, RelationProperty
from items.views.base import generic_edit


@login_required
def relation_list(request):

    relations = ItemRelation.objects.filter(author=request.user.setting)

    return JsonResponse(
        {
            "result": {
                "relations": list(relations.serialize()),
                "headers": header_for_table(ItemRelation),
            },
            "count": relations.count(),
        }
    )


@login_required
def relation_details(request, id):

    relation = ItemRelation.objects.filter(author=request.user.setting, id=id).first()

    if not relation:
        return JsonResponse({}, status=404)

    return JsonResponse(
        {
            "object": relation.serialize(),
            "parent": relation.parent.serialize(),
            "parent_headers": header_for_table(Item),
            "child": relation.child.serialize(),
            "child_headers": header_for_table(Item),
            "properties": list(relation.properties.serialize()),
            "properties_headers": header_for_table(Property),
            "relation_properties": list(relation.relation_properties.serialize()),
            "relation_properties_headers": header_for_table(RelationProperty),
        }
    )


@login_required
def relation_edit(request, id=None):
    """Create/edit relation view."""

    return generic_edit(ItemRelation, request, id)
