from django.core.urlresolvers import reverse

from .. import schema
from ..fields import PlainField
from ..utils import IconModelWrapper

from .base import DomainObject, DomainObjectList, Manager
from .registry import domain_objects, domain_object_lists


__all__ = ('Icon', 'IconList')


class IconManager(Manager):
    def __init__(self, is_big):
        super(IconManager, self).__init__()
        self.is_big = is_big

    def get_domain_object_list(self, domain_object_list_class, role_registry,
                               user):
        return domain_object_list_class(
            user=user, role_registry=role_registry, is_big=self.is_big
        )


@domain_objects.register
class Icon(DomainObject):
    model_class = 'achievery.Icon'

    id = PlainField(schema_type=schema.TYPE.NUMBER)
    data = PlainField(schema_type=schema.TYPE.STRING)
    level = PlainField(schema_type=schema.TYPE.NUMBER)
    is_big = PlainField(schema_type=schema.TYPE.BOOLEAN)
    mime_type = PlainField(schema_type=schema.TYPE.STRING)

    big = IconManager(is_big=True)
    small = IconManager(is_big=False)

    def delete(self):
        self.model.delete()

    @property
    def url(self):
        # noinspection PyTypeChecker
        size = ['small', 'big'][self.is_big]
        return reverse(
            'achievery:icon_raw', kwargs={'pk': self.id, 'size': size}
        )


@domain_object_lists.register
class IconList(DomainObjectList):
    domain_object_class = Icon

    def wrap(self, model):
        wrapped_model = IconModelWrapper(model, self.context.get('is_big'))
        return self.domain_object_class(
            self.user, wrapped_model, self.role_registry)
