from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from api.serializers import ZoneSerializer, ZoneUpdateSerializer
from api.serializers import SubnetSerializer, SubnetUpdateSerializer
from api.serializers import BlockSerializer, BlockUpdateSerializer
from api.serializers import IPSerializer, IPUpdateSerializer
from api.models import Zone, Subnet, Block, IP

class CIDRModelViewSet(viewsets.ModelViewSet):
    filter_fields = ('name', )

    def get_serializer_class(self):
        serializer_class = self.serializer_class

        if self.request.method == 'PUT':
            serializer_class = self.update_serializer_class

        return serializer_class

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def get_queryset(self):
        """
        Override get_queryset() to filter on multiple values for 'id'
        """

        queryset = self.queryset
        id_value = self.request.QUERY_PARAMS.get('id', None)

        if id_value:
            id_list = id_value.split(',')
            queryset = queryset.filter(id__in=id_list)

        return queryset

class ZoneViewSet(CIDRModelViewSet):
    """
    API endpoint that allows zones to be viewed or edited.
    """
    queryset = Zone.objects.all()
    serializer_class = ZoneSerializer
    update_serializer_class = ZoneUpdateSerializer

class SubnetViewSet(CIDRModelViewSet):
    """
    API endpoint that allows subnets to be viewed or edited.
    """
    queryset = Subnet.objects.all()
    serializer_class = SubnetSerializer
    update_serializer_class = SubnetUpdateSerializer

class BlockViewSet(CIDRModelViewSet):
    """
    API endpoint that allows subnets to be viewed or edited.
    """
    queryset = Block.objects.all()
    serializer_class = BlockSerializer
    update_serializer_class = BlockUpdateSerializer

class IPViewSet(CIDRModelViewSet):
    """
    API endpoint that allows IPs to be viewed or edited.
    """
    queryset = IP.objects.all()
    serializer_class = IPSerializer
    update_serializer_class = IPUpdateSerializer
