import logging

from django.conf import settings

from staff.person_avatar.models import PreprofileExtraFields
from .base import (
    BaseAvatar,
    BaseAvatarCollection,
    AvatarCollectionError,
    MAIN, AVATAR, GRAVATAR,
)

logger = logging.getLogger(__name__)


class PreprofileAvatar(BaseAvatar):
    metadata_owner_field = 'preprofile'

    AVATARS_MAX_COUNT = 5

    @property
    def owner_login(self):
        return self.owner.login

    @property
    def owner_work_email(self):
        return self.owner and '{login}@{domain}'.format(
            login=self.owner.login,
            domain=self.owner.email_domain,
        )

    def old_login_work_email(self, old_login):
        return self.owner and '{login}@{domain}'.format(
            login=old_login,
            domain=self.owner.email_domain,
        )

    def get_extrafields_instance(self):
        return (
            PreprofileExtraFields.objects
            .get_or_create(preprofile=self.owner)
        )[0]

    def avatar_id(self, attr=None, old_login=None):
        if old_login is None or attr is None:
            return super(PreprofileAvatar, self).avatar_id(attr=attr)

        if self.metadata.id is None:
            raise Exception('Metadata is unsaved')

        if attr == GRAVATAR:
            if self.owner_work_email:
                return self.gravatar_id(self.old_login_work_email(old_login))
            else:
                return None

        return '{login}-{attr}'.format(login=old_login, attr=attr)


class PreprofileAvatarCollection(BaseAvatarCollection):
    avatar_class = PreprofileAvatar

    # initial_qs = (
    #     AvatarMetadata.objects
    #     .filter(is_deleted=False)  # person=None?
    #     .exclude(preprofile=None)
    # )

    def post_upload(self, new_avatar):
        """Make it avatar, gravatar and main"""
        self.make(new_avatar.id, [MAIN, AVATAR])
        if self.count() > 1:
            self.delete(pk=self.first().id)

    def make(self, pk, marks, old_login=None):
        if old_login is None:
            return super(PreprofileAvatarCollection, self).make(pk, marks)

        marks = {MAIN, AVATAR} & set(marks)
        if AVATAR in marks:
            marks.add(GRAVATAR)

        avatar = self.get(pk)
        for mark in marks:
            try:
                storage_id = avatar.avatar_id(attr=mark, old_login=old_login)
                avatar.delete_from_storage(storage_id)
            except AvatarCollectionError:
                pass

        avatar.mark_and_make(marks)

    def get_link_for(self, search_field, search_value):
        try:
            avatar = self.get_by_field(search_field, search_value)
        except AvatarCollectionError:
            return ''
        return self.get_link_for_id(avatar.id)

    @staticmethod
    def get_link_for_id(avatar_id):
        return 'https://{center_url}/api/v1/user/preprofile/photo_{id}/original.jpg'.format(
            center_url=settings.CENTER_MASTER,
            id=avatar_id,
        )
