from rest_framework import serializers

from devices.enums import DeviceType
from devices.fields import DeviceRelatedField, DeviceGroupRelatedField
from devices.models.device import Device, DeviceGroup
from devices.services.endpoint.endpoint_get_status import EndpointStatusService
from devices.services.firewall import FirewallService
from devices.services.sensor.service import SensorService


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

    class Meta:
        model = Device
        fields = ['id', 'name', 'description', 'type', 'ip', 'port', 'updated', 'status', 'group']

    def get_status(self, device: Device):
        if device.type == DeviceType.FIREWALL:
            return FirewallService(device).check_status()

        elif device.type == DeviceType.ENDPOINT:
            return EndpointStatusService(device).get_status()

        elif device.type == DeviceType.SENSOR:
            return SensorService(device).get_status()


class DeviceGroupSerializer(serializers.ModelSerializer):
    devices = DeviceRelatedField(many=True, queryset=Device.objects.all(), default=[])

    class Meta:
        model = DeviceGroup
        fields = ['id', 'name', 'description', 'devices']


class ExportToCSVDeviceSerializer(serializers.ModelSerializer):
    group = serializers.ReadOnlyField(source='group.name', allow_null=True)

    class Meta:
        model = Device
        # You need to explicitly list all fields, because then this list is passed to the function csv_export
        # to create columns
        fields = ['id', 'type', 'name', 'description', 'ip', 'port', 'group', 'updated']
