from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import TableAllDevCmdDefine, TableDevCmdNamePoll, TableSoftLimitAngle, TableXproAllDevinfo


class TableAllDevCmdDefineSerializer(ModelSerializer):
    class Meta:
        model = TableAllDevCmdDefine
        fields = '__all__'


class TableDevCmdNamePollSerializer(ModelSerializer):
    class Meta:
        model = TableDevCmdNamePoll
        fields = '__all__'


class TableSoftLimitAngleSerializer(ModelSerializer):

    def validate_remarks(self, value):
        """
        当传过来的值为 none 时，则在数据库里存一个空值
        
        @param value: 通过基本校验之后的值
        """
        if value == "none":
            return "" 
        return value

    class Meta:
        model = TableSoftLimitAngle
        fields = '__all__'


class TableXproAllDevinfoSerializer(ModelSerializer):

    def allow_none(self, value):
        """
        当传过来的值为 none 时，则在数据库里存一个空值
        
        @param value: 通过基本校验之后的值
        """
        if value == "none":
            return "" 
        return value

    def validate(self, attrs: dict):
        """
        校验字段，在进行基础校验之后，如果字段名称为下面的字段，
        且当传过来的值为 none 时，存一个空值
        
        @param attrs: 通过基本校验之后的值
        """
        for field_name, value in attrs.items():
            if field_name in (['cmd_excel_path', 'udp_ip_src', 'udp_ip_dst',
                               'udpmc_ip', 'udpmc_ip_tx', 'udpmc_ip_rx', 'remarks']):
                attrs[field_name] = self.allow_none(value)
        return attrs

    class Meta:
        model = TableXproAllDevinfo
        fields = '__all__'
