from app.entities import models
from rest_framework import viewsets, status
from rest_framework.response import Response
from django_filters import rest_framework as filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from app.applicationlayer.ams.asset_group.table_filters import AssetGroupFilter
from app.applicationlayer.ams.asset_group import serializers
from app.applicationlayer.utils import (
    CustomPagination, status_message_response
)
from app.helper import decorators
from django.db import transaction


class AssetGroupViewset(viewsets.ModelViewSet):

    queryset = models.AssetGroup.objects.all()
    serializer_class = serializers.AssetGroupSerializer
    pagination_class = CustomPagination
    lookup_field = "code"
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
    ordering_fields = '__all__'
    search_fields = (
        'code', 'name', 'asset_group'
    )

    @transaction.atomic
    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        message = status_message_response(
            201, 'success',
            'New Asset Group created', serializer.data
        )

        return Response(
            message
        )

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)

            message = status_message_response(
                200,
                'success',
                'List of Asset Groups found!',
                serializer.data
            )

            return self.get_paginated_response(message)

        serializer = self.get_serializer(self.queryset, many=True)

        return Response(
            serializer.data,
            status=status.HTTP_200_OK
        )
    
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    @transaction.atomic
    def destroy(self, request, *args, **kwargs):

        instance = self.get_object()
        self.perform_destroy(instance)

        return Response(status=status.HTTP_204_NO_CONTENT)