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


@login_required
def item_list(request):

    items = Item.objects.filter(author=request.user.setting)
    types = ItemType.objects.filter(author=request.user.setting)

    return JsonResponse(
        {
            "result": {
                "items": list(items.serialize()),
                "items_headers": header_for_table(Item),
                "types": list(types.serialize()),
                "types_headers": header_for_table(ItemType),
            },
            "count": items.count() + types.count(),
        }
    )


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

    return generic_edit(Item, request, id)


@login_required
def item_details(request, id):

    item = Item.objects.filter(author=request.user.setting, id=id).first()

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

    return JsonResponse(
        {
            "object": item.serialize(),
            "headers": header_for_table(Item),
            "parents": list(item.parents.serialize()),
            "parents_headers": header_for_table(ItemRelation),
            "children": list(item.children.serialize()),
            "children_headers": header_for_table(ItemRelation),
            "properties": list(item.properties.serialize()),
            "properties_headers": header_for_table(Property),
            "linked_properties": list(item.linked_properties.serialize()),
            "linked_properties_headers": header_for_table(LinkedProperty),
        }
    )


@login_required
def item_history(request, id):

    item = Item.objects.filter(author=request.user.setting, id=id).first()

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

    headers = [field for field in Item.objects.headers().keys() if field not in ["id", "history"]]
    headers.extend(["history_id", "history_date"])

    qs = item.history.order_by("-history_date").values(*headers)
    return JsonResponse(
        {
            "object": item.serialize(),
            "headers": header_for_table(Item),
            # Return only the last 50 versions
            "history": list(qs[:50]),
        }
    )


@login_required
def item_history_edit(request, id, hid):

    item = Item.objects.filter(author=request.user.setting, id=id).first()

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

    version = item.history.filter(history_user=request.user.setting, history_id=hid).first()

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

    if request.method == "DELETE":
        try:
            version.delete()
        except Exception:
            return JsonResponse({}, status=401)

        return JsonResponse({})

    if request.method == "POST":
        try:
            version.instance.save(force_update=True)

        except Exception:
            return JsonResponse({}, status=401)

        return JsonResponse(
            {
                "object": version.instance.serialize(),
            }
        )

    return JsonResponse({}, status=405)
