from plone.app.z3cform.interfaces import IEmailWidget
from plone.app.z3cform.widgets.email import EmailWidget
from ploneintranet.layout.interfaces import IPloneintranetFormLayer
from ploneintranet.schema.interfaces import IPIEmail
from ploneintranet.schema.interfaces import ITelephone
from z3c.form.browser.text import TextWidget
from z3c.form.interfaces import IFieldWidget
from z3c.form.interfaces import ITextWidget
from z3c.form.widget import FieldWidget
from zope.component import adapter
from zope.interface import implementer
from zope.interface import implementer_only
from zope.schema.interfaces import IURI


class IPIEmailWidget(IEmailWidget):
    """Marker interface for a custom email widget"""


@implementer_only(IPIEmailWidget)
class PIEmailWidget(EmailWidget):
    """Support email fields our way"""

    type = "email"
    klass = ""


@implementer(IFieldWidget)
@adapter(IPIEmail, IPloneintranetFormLayer)
def PIEmailFieldWidget(field, request):
    return FieldWidget(field, PIEmailWidget(request))


class ITelephoneWidget(ITextWidget):
    """Marker interface for a custom telephone widget"""


@implementer_only(ITelephoneWidget)
class TelephoneWidget(TextWidget):
    """Support phone fields.

    These exist in neither zope.schema, z3c.form, nor in plone.app.z3cform.
    """

    type = "tel"
    klass = ""


@implementer(IFieldWidget)
@adapter(ITelephone, IPloneintranetFormLayer)
def TelephoneFieldWidget(field, request):
    return FieldWidget(field, TelephoneWidget(request))


class IPIURIWidget(ITextWidget):
    """Marker interface for a custom URI widget"""


@implementer_only(IPIURIWidget)
class PIURIWidget(TextWidget):
    """Support URL-like fields.

    Exists in zope.schema, not z3c.form.
    There is a LinkWidget in plone.app.z3cform, but we are not using that.

    Note that the type constraint is actually invalid for non-URL URIs. But
    binding to IRUI is already firmly entrenched our code.
    """

    type = "url"  # widget is uri, type is url
    klass = "url"


@implementer(IFieldWidget)
@adapter(IURI, IPloneintranetFormLayer)
def PIURIFieldWidget(field, request):
    return FieldWidget(field, PIURIWidget(request))
