from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from template.serializers import ImageTemplateModelSerializer, ImageTemplateListItemSerializer
from template.models import ImageTemplate
from django.db.models import Q
from rest_framework.permissions import IsAuthenticated


class ImageTemplateViewSet(ModelViewSet):
    serializer_class = ImageTemplateModelSerializer
    queryset = ImageTemplate.objects.all()
    permission_classes = [IsAuthenticated]

    def create(self, request):
        # TODO: Check the permissions to create template and using the flavors and leases
        serializer = ImageTemplateModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        new_template = ImageTemplate(
            name=data["name"],
            description=data["description"],
            access_protocol=data["access_protocol"],
            system_type=data["system_type"],
            distro=data["distro"],
            created_by=request.user,
            image=data["image"],
            lease=data["lease"],
            flavor=data["flavor"],
            type="IMAGE"
        )
        new_template.save()
        serializer = ImageTemplateModelSerializer(instance=new_template)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        # only the name, description, lease, flavor can be updated
        allowed_keys = ["name", "description", "access_prtotocol", "distro", "lease", "flavor"]

        # delete not allowed key
        for key in request.data.keys():
            if key not in allowed_keys:
                request.data.pop(key, None)

        return super(ImageTemplateViewSet, self).update(request, partial=True)

    def list(self, request, *args, **kwargs):
        # TODO: Filter for shared tempaltes
        query = ImageTemplate.objects.filter(Q(created_by=request.user.id) | Q(type="SYSTEM"))
        serializer = ImageTemplateListItemSerializer(query, many=True)
        return Response(serializer.data)