from plone.autoform.interfaces import IFormFieldProvider
from plone.dexterity.interfaces import IDexterityContent
from plone.supermodel import model
from ploneintranet.core import _
from zope import schema
from zope.component import adapter
from zope.interface import alsoProvides
from zope.interface import implementer
from zope.interface import Interface
from zope.interface import noLongerProvides
from zope.interface import provider


@provider(IFormFieldProvider)
class IPinningBehavior(model.Schema):
    """Behavior for pinning content."""

    pinned = schema.Bool(
        title=_("label_pinned", default="Pinned"),
        description=_(
            "description_pinned",
            default="Pin this content to appear on top of listings.",
        ),
        required=False,
        default=False,
    )


@implementer(IPinningBehavior)
@adapter(IDexterityContent)
class PinningBehavior:
    """This adapter allows z3c.form to mark an object as a Pinned

    Instead of storing the value in an attribute,
    it applies or removes a marker interface
    """

    def __init__(self, context):
        self.context = context

    @property
    def pinned(self):
        return IPinned.providedBy(self.context)

    @pinned.setter
    def pinned(self, value):
        if value is True:
            alsoProvides(self.context, IPinned)
        else:
            noLongerProvides(self.context, IPinned)


class IPinned(Interface):
    """Marker Interface to state if an object is pinned"""
