# -*- coding: utf-8 -*-
# Copyright (c) 2013  Infrae. All rights reserved.
# See also LICENSE.txt

from zope.component import queryUtility
from zope.interface.interfaces import IInterface

from Products.Formulator.DummyField import fields
from Products.Formulator.Field import ZMIField
from Products.Formulator.Validator import Validator
from Products.Formulator.Widget import Widget
from Products.Formulator.Widget import render_element


class InterfaceValidator(Validator):
    """Formulator validator for an interface.
    """
    property_names = Validator.property_names + ['required']
    message_names = Validator.message_names + [
        'required_not_found', 'invalid_interface']

    required = fields.CheckBoxField(
        'required',
        title='Required',
        description=(
            u"Checked if the field is required; the user has to fill in some "
            u"data."),
        default=1)

    invalid_interface = u"Input is not a valid interface."
    required_not_found = u"Input is required but no input given."

    def validate(self, field, key, REQUEST):
        value = REQUEST.get(key)
        if value is None:
            if field.get_value('required'):
                self.raise_error('required_not_found', field)
            return None
        interface = queryUtility(IInterface, name=value.strip())
        if interface is None:
            self.raise_error('invalid_interface', field)
        return interface


class InterfaceWidget(Widget):

    default = fields.InterfaceField(
        'default',
        title='Default',
        description='default value',
        default=None,
        required=0)

    def render(self, field, key, value, REQUEST):
        """Render text input field.
        """
        kw = {'type': "text",
              'name': key,
              'css_class': field.get_value('css_class'),
              'value': value is not None and value.__identifier__ or "",
              'size': 20,
              'id': field.generate_field_html_id(key)}
        return render_element("input", **kw)


class InterfaceField(ZMIField):
    """Formulator field to select an interface.
    """
    meta_type = "InterfaceField"
    widget = InterfaceWidget()
    validator = InterfaceValidator()
