from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, ListModelMixin, DestroyModelMixin
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from core.mixins import ApiPermissionCheckMixin, ExportToCsvMixin
from devices.filters import DeviceFilter
from devices.models.device import Device, DeviceGroup
from devices.serializers.device import DeviceSerializer, DeviceGroupSerializer
from devices.services.vector import VectorService


class DeviceViewSet(ApiPermissionCheckMixin,
                    ExportToCsvMixin,
                    RetrieveModelMixin,
                    UpdateModelMixin,
                    ListModelMixin,
                    DestroyModelMixin,
                    GenericViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer
    filterset_class = DeviceFilter

    def perform_update(self, serializer):
        device = serializer.save()
        vector = VectorService(device)
        vector.update_config()

    def perform_destroy(self, device):
        vector = VectorService(device)
        vector.delete_config()
        device.delete()


class DeviceGroupViewSet(ApiPermissionCheckMixin, ModelViewSet):
    queryset = DeviceGroup.objects.all()
    serializer_class = DeviceGroupSerializer
