from plone.app.z3cform.converters import RelatedItemsDataConverter
from plone.app.z3cform.widgets.relateditems import RelatedItemsWidget
from ploneintranet.layout.interfaces import IPloneintranetFormLayer
from z3c.form.interfaces import IFieldWidget
from z3c.form.widget import FieldWidget
from z3c.relationfield.interfaces import IRelationList
from zope.component import adapter
from zope.interface import implementer
from zope.schema.interfaces import ICollection


class PIRelatedItemsWidget(RelatedItemsWidget):
    pass


@implementer(IFieldWidget)
@adapter(IRelationList, IPloneintranetFormLayer)
def PIRelatedItemsFieldWidget(field, request, extra=None):
    if extra is not None:
        request = extra
    return FieldWidget(field, PIRelatedItemsWidget(request))


@adapter(ICollection, PIRelatedItemsWidget)
class PIRelatedItemsDataConverter(RelatedItemsDataConverter):
    """
    Convert between the string representation of a list of related items and
    the list of related items.

    This widget is used in ploneintranet.news, see the carousel_slides field.
    It's a complex widget that is not yet exposed in the component library.
    """

    def toFieldValue(self, value):
        """The widget expects a list of uids joined by `self.widget.separator`"""
        if isinstance(value, (list)):
            value = self.widget.separator.join(value)
        return super().toFieldValue(value)
