import logging

from staff.achievery.domain import GivenAchievement
from staff.achievery.permissions import RoleRegistry
from staff.achievery.serializers import GivenAchievementSerializer


logger = logging.getLogger(__name__)


class Result(object):
    def __init__(self, obj=None, success=None, error=None):
        self.object = obj
        self.success = success
        self.error = error

    def __bool__(self):
        return bool(self.success)


class AchievementMassGiver(object):
    def __init__(self, params, achievement, author):
        self.claims = params
        self.achievement = achievement
        self.author = author

    def __iter__(self):
        for claim in self.claims:
            login = claim['login']
            level = claim['level']
            comment = claim['comment']

            try:
                roles = RoleRegistry(user=self.author)
                given = GivenAchievement(
                    user=self.author,
                    model=GivenAchievement.get_model_class()(),
                    role_registry=roles,
                )
                serializer = GivenAchievementSerializer(
                    given,
                    data={
                        'achievement': {'id': self.achievement.id},
                        'person': {'login': login},
                        'comment': comment,
                        'level': level,
                    },
                    context={
                        'user': self.author,
                        'role_registry': roles,
                    },
                )
                if serializer.is_valid():
                    serializer.save()
                    yield Result(obj=claim, success=True)
                else:
                    yield Result(obj=claim, error=serializer.errors)

            except Exception as e:
                logger.exception("Error giving achievement")
                yield Result(obj=claim, error=e)

    def give(self):
        return list(self)
