from rest_framework import serializers

from .. import exceptions

from .achievement import (
    AchievementSerializer,
    PaginatedAchievementSerializer
)
from .base import DynamicFieldsSerializer
from .event import EventSerializer
from .icon import IconSerializer
from .person import PersonSerializer


class GivenAchievementSerializer(DynamicFieldsSerializer):
    id = serializers.IntegerField(read_only=True)
    achievement = AchievementSerializer()
    person = PersonSerializer()
    comment = serializers.CharField(required=False)
    comment_html = serializers.CharField(required=False)
    is_hidden = serializers.BooleanField(required=False)
    is_active = serializers.BooleanField(required=False)
    level = serializers.IntegerField(required=False)
    revision = serializers.IntegerField(required=False)
    slot = serializers.IntegerField(required=False)
    icon_big = IconSerializer(read_only=True)
    icon_small = IconSerializer(read_only=True)
    events = EventSerializer(many=True, read_only=True)
    last_event_at = serializers.DateTimeField(required=False)

    roles = serializers.Field(source='_roles')

    def restore_object(self, attrs, instance=None):
        requested = attrs.get('revision')
        present = getattr(instance, 'revision')
        if getattr(instance, 'id', None) and requested != present:
            raise exceptions.ConcurrentModification(data={
                'requested revision': requested, 'actual revision': present
            })

        return super(GivenAchievementSerializer, self).restore_object(attrs,
                                                                      instance)


class PaginatedGivenAchievementSerializer(PaginatedAchievementSerializer):
    class Meta:
        object_serializer_class = GivenAchievementSerializer
