from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from common.utils.serializers import BaseDataV3Serializer
from common.utils.encryption import imei_md5


class AcrelADW300HJ4GSerializer(serializers.Serializer):
    imei = serializers.CharField(max_length=32, help_text="imei号")
    iccid = serializers.CharField(required=False,
                                  default=None,
                                  allow_null=True,
                                  max_length=32,
                                  help_text="iccid")
    data = BaseDataV3Serializer(required=False, many=True)
    v = serializers.CharField(max_length=16, help_text="md5校验")
    alarm = serializers.NullBooleanField(required=False, help_text="断电告警")
    time = serializers.DateTimeField(required=False, help_text="时间戳")

    def validate(self, attrs):
        sn = attrs.get("imei")
        dt_md5 = imei_md5(sn, "acrel")
        if dt_md5 != attrs.get("v"):
            raise ValidationError
        return attrs
