import logging

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from core.validators import ValidateFileExtension
from devices.fields import DeviceGroupRelatedField
from devices.models.device import DeviceGroup
from devices.models.sensor import ArmaSensor
from devices.services.sensor.service import SensorService

_log = logging.getLogger(__name__)


class CreateSensorSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArmaSensor
        fields = ['name', 'ip', 'port']


class SensorSerializer(serializers.ModelSerializer):
    group = DeviceGroupRelatedField(queryset=DeviceGroup.objects.all(), default=None, allow_null=True)
    status = serializers.SerializerMethodField()

    class Meta:
        model = ArmaSensor
        fields = '__all__'

    def get_status(self, endpoint: ArmaSensor) -> dict:
        return SensorService(endpoint).get_status()

    def validate_span_interface(self, span_interface):
        actually_interfaces = SensorService(sensor=self.instance).get_interfaces()
        interfaces_names = [interface['interface'] for interface in actually_interfaces['data']]

        if span_interface in interfaces_names:
            return span_interface
        raise ValidationError('select actually span interface')


class ZeekProtocolsDisableSerializer(serializers.Serializer):
    """Serializer validate upload protocol list."""
    disable_protocols = serializers.ListField(child=serializers.CharField(), default=[])


class ZeekSettingsUpdateSerializer(serializers.Serializer):
    """Serializer validate upload local.zeek file."""
    file = serializers.FileField(validators=[ValidateFileExtension(allowed_extensions=[".zeek"])])
