# coding=utf-8

from django.conf import settings

from rest_framework import serializers

from apps.images.models import Images
from apps.activity.models import Activity

from utils.exceptions import CustomError


class ActivitySerializer(serializers.ModelSerializer):
    cover_url = serializers.SerializerMethodField()
    create_user_t = serializers.CharField(source='create_user.name', read_only=True)

    def get_cover_url(self, obj):
        if obj.cover:
            return '{}{}'.format(settings.MEDIA_URL, obj.cover.picture)
        return ''

    class Meta:
        model = Activity
        fields = '__all__'

    def create(self, validated_data):
        cover = self.initial_data.get('image', None)
        validated_data['create_user'] = self.context['request'].user
        if not cover:
            raise CustomError(u'请上传封面！')
        validated_data['cover'] = Images.objects.employee_addnew(validated_data['create_user'], Images.ACTIVITY_COVER, cover)
        instance = super(ActivitySerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        old_cover = None
        cover = self.initial_data.get('image', None)
        if cover:
            old_cover = instance.cover
            validated_data['cover'] = Images.objects.employee_addnew(self.context['request'].user, Images.ACTIVITY_COVER, cover)
        instance = super(ActivitySerializer, self).update(instance, validated_data)
        if old_cover:
            old_cover.del_images()
        return instance
