from django.conf import settings
from django.utils.translation import gettext as _

from rest_framework import serializers

from ..models.ProfileModel import ProfileModel


class ProfileSerializer(serializers.ModelSerializer):

    username = serializers.ReadOnlyField(source='user.username')
    avatar = serializers.ImageField(required=False)

    class Meta:
        model = ProfileModel
        fields = ["username", "avatar", "user_id"]

    def validate_avatar(self, value):
        '''
        Check that the image is not too large
        '''
        if value.size > settings.PROFILE_PICTURE_MAX_SIZE:
            raise serializers.ValidationError(_('Image is too large.'))
        return value

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['avatar'] = data['avatar'][data['avatar'].find('/static/'):]
        return data
