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 LinkedProperty, Property, RelationProperty
from items.views.base import generic_edit


@login_required
def property_list(request):

    properties = Property.objects.filter(author=request.user.setting)
    linked_properties = LinkedProperty.objects.filter(author=request.user.setting)
    relation_properties = RelationProperty.objects.filter(author=request.user.setting)

    return JsonResponse(
        {
            "result": {
                "properties": list(properties.serialize()),
                "properties_headers": header_for_table(Property),
                "linked_properties": list(linked_properties.serialize()),
                "linked_properties_headers": header_for_table(LinkedProperty),
                "relation_properties": list(relation_properties.serialize()),
                "relation_properties_headers": header_for_table(RelationProperty),
            },
            "count": properties.count() + linked_properties.count() + relation_properties.count(),
        }
    )


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

    return generic_edit(Property, request, id)


@login_required
def linked_property_edit(request, id=None):
    """Create/edit linked property view."""

    return generic_edit(LinkedProperty, request, id)


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

    return generic_edit(RelationProperty, request, id)
