from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS_BASE, EXCLUDE_FIELDS_DEPT
from .models import Drain, DrainEquip, EnvData
from apps.em.serializers import EquipmentSerializer
from rest_framework import serializers
from django.utils import timezone


class DrainSerializer(CustomModelSerializer):
    """Serializer for Drain model"""

    class Meta:
        model = Drain
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_DEPT

    def validate(self, attrs):
        attrs['belong_dept'] = attrs['mgroup'].belong_dept
        return super().validate(attrs)


class DrainEquipSerializer(CustomModelSerializer):
    equipment_type = serializers.CharField(
        source='equipment.type', read_only=True)
    equipment_name = serializers.CharField(
        source='equipment.name', read_only=True)

    class Meta:
        model = DrainEquip
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_BASE


class EnvDataSerializer(CustomModelSerializer):
    """Serializer for EnvData model"""

    class Meta:
        model = EnvData
        fields = "__all__"


class DrainEquipEnvSerializer(CustomModelSerializer):
    equipment_type = serializers.CharField(
        source='equipment.type', read_only=True)
    equipment_name = serializers.CharField(
        source='equipment.name', read_only=True)
    equipment_envdata = serializers.SerializerMethodField()

    def get_equipment_envdata(self, obj):
        now = timezone.now()
        now_10_before = now - timezone.timedelta(minutes=10)
        obj = EnvData.objects.filter(
            equipment=obj.equipment, time__gte=now_10_before, time__lte=now).order_by('-time').first()
        if obj:
            return EnvDataSerializer(instance=obj).data
        else:
            return {}

    class Meta:
        model = DrainEquip
        fields = ['equipment', 'equipment_type',
                  'equipment_name', 'equipment_envdata']
