from .. import models
from ..utils import IconModelWrapper

from .plain import PlainField


class IconField(PlainField):
    def __init__(self, is_big, *args, **kwargs):
        super(IconField, self).__init__(*args, **kwargs)
        self.is_big = is_big

    def get(self, instance, owner):
        from ..domain import Icon
        if hasattr(instance, 'level'):  # It's a Given
            level = instance.level
            achievement_id = instance.achievement.model.id
        else:  # It's an Achievement
            level = -1
            achievement_id = instance.model.id

        lookup = {'achievement_id': achievement_id, 'level': level}
        try:
            model = models.Icon.objects.get(**lookup)
        except models.Icon.DoesNotExist:
            return None
        return Icon(user=instance.user, role_registry=instance.role_registry,
                    model=IconModelWrapper(model, is_big=self.is_big))
