# coding=utf-8

from rest_framework import serializers
from apps.customer.models import CustomerAddress
from utils.exceptions import CustomError


class AddressSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustomerAddress
        fields = '__all__'

    def create(self, validated_data):
        validated_data['customer'] = self.context['request'].customer
        if validated_data['default']:
            CustomerAddress.objects.filter(customer=validated_data['customer']).update(default=False)
        instance = super(AddressSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'该收货地址已被删除，禁止重复操作！')
        if validated_data['default']:
            CustomerAddress.objects.filter(customer=instance.customer).update(default=False)
        instance = super(AddressSerializer, self).update(instance, validated_data)
        return instance
