from functools import partial
from plone import api
from plone.base.permissions import AddPortalContent
from plone.memoize.view import memoize_contextless
from ploneintranet import api as pi_api
from ploneintranet.core import _
from ploneintranet.imagebank.interfaces import IImageBankCollectionContainer
from ploneintranet.imagebank.interfaces import IImageBankFolder
from zope.interface import implementer
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleTerm
from zope.schema.vocabulary import SimpleVocabulary


class CollectionSimpleTerm(SimpleTerm):
    """Extend the simple term with optgroup and disabled attributes."""

    def __init__(self, value, token=None, title=None, optgroup="", disabled=False):
        """Custom term that adds optgroup and disabled attributes."""
        super().__init__(value, token, title)
        self.optgroup = optgroup
        self.disabled = disabled


@implementer(IVocabularyFactory)
class CollectionsVocabularyFactory:
    """Vocabulary factory for collections"""

    @property
    @memoize_contextless
    def shared_collections(self):
        """Returns a vocabulary of shared collections"""
        terms = []
        collection_containers = api.content.find(
            object_provides=IImageBankCollectionContainer
        )
        paths = [
            collection_container.getPath()
            for collection_container in collection_containers
        ]
        shared_collections = api.content.find(
            path=paths,
            object_provides=IImageBankFolder,
            sort_on="sortable_title",
        )
        term_factory = partial(
            CollectionSimpleTerm, optgroup=_("label_shared", default="Shared")
        )
        for collection in shared_collections:
            if api.user.has_permission(AddPortalContent, obj=collection.getObject()):
                terms.append(
                    term_factory(
                        value=collection.UID,
                        title=collection.Title,
                    )
                )
        return terms

    @property
    @memoize_contextless
    def private_collections(self):
        """Returns a vocabulary of private collections"""
        terms = []
        userprofile = pi_api.userprofile.get_current()
        private_collections = api.content.find(
            context=userprofile,
            object_provides=IImageBankFolder,
            sort_on="sortable_title",
        )
        term_factory = partial(
            CollectionSimpleTerm, optgroup=_("label_private", default="Private")
        )
        for collection in private_collections:
            terms.append(
                term_factory(
                    value=collection.UID,
                    title=collection.Title,
                )
            )
        return terms

    def __call__(self, context):
        """Returns a vocabulary of collections"""
        terms = self.shared_collections + self.private_collections
        parent_uid = context.aq_parent.UID()
        for term in terms:
            if term.value == parent_uid:
                term.disabled = True
        return SimpleVocabulary(terms)


collection_vocabulary = CollectionsVocabularyFactory()
