import logging

from django.utils.translation import gettext_lazy
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from core.mixins import ApiPermissionCheckMixin
from perms.models import Perm
from .models import Receiver, SyslogReceiver, OpcuaReceiver
from .serializers import SyslogReceiverSerializer, OpcuaReceiverSerializer, ChangeStateReceiverSerializer

_log = logging.getLogger(__name__)


class ChangeExportStatusActionMixin:
    """
        A mixin that adds the ability (as an action) to bulk change the export state for selected receivers.
        Separated into a mixin so that it can be added to multiple viewsets.
        Since there are different viewsets for OPCUA receivers and SYSLOG receivers.
        Gets a list of receivers IDs and changes their status to the one specified in the request body.
    """
    @action(methods=['POST'], detail=False)
    def change_state(self, request, *args, **kwargs):
        serializer = ChangeStateReceiverSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        ids_to_change = serializer.validated_data['ids']
        new_export_status = serializer.validated_data['status']
        receivers_to_change = self.queryset.filter(id__in=ids_to_change).values_list('receiver_id', flat=True)
        Receiver.objects.filter(pk__in=receivers_to_change).update(export_status=new_export_status)
        _log.info(f'Export status changed to {new_export_status} for following receivers: {receivers_to_change}')
        return Response()


class SyslogReceiverViewSet(ApiPermissionCheckMixin,
                            ChangeExportStatusActionMixin,
                            ModelViewSet,
                            GenericViewSet):
    console_permissions = [Perm.can_export_events]
    message = gettext_lazy('Cannot access syslog Receivers. Permission denied')
    serializer_class = SyslogReceiverSerializer
    queryset = SyslogReceiver.objects.all()


class OpcuaReceiverViewSet(ApiPermissionCheckMixin,
                           ChangeExportStatusActionMixin,
                           ModelViewSet,
                           GenericViewSet):
    console_permissions = [Perm.can_export_events]
    message = gettext_lazy('Cannot access OPCUA Receivers. Permission denied')
    serializer_class = OpcuaReceiverSerializer
    queryset = OpcuaReceiver.objects.all()
