##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Utilities for the 'nested directive' section in the narrative docs.
"""

from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import implementer
from zope.schema import Id
from zope.schema import Int
from zope.schema import NativeStringLine
from zope.schema import Text
from zope.schema import TextLine

from zope.configuration.config import GroupingContextDecorator
from zope.configuration.fields import Bool


schema_registry = {}


class ISchemaInfo(Interface):
    """Parameter schema for the schema directive
    """

    name = TextLine(
        title="The schema name",
        description="This is a descriptive name for the schema.",
    )

    id = Id(title="The unique id for the schema")


class ISchema(Interface):
    """Interface that distinguishes the schema directive
    """

    fields = Attribute("Dictionary of field definitions")


@implementer(ISchema)
class Schema(GroupingContextDecorator):
    """Handle schema directives
    """

    def __init__(self, context, name, id):
        self.context, self.name, self.id = context, name, id
        self.fields = {}

    def after(self):
        schema = Interface.__class__(
            self.name,
            (Interface, ),
            self.fields
        )
        schema.__doc__ = self.info.text.strip()
        self.action(
            discriminator=('schema', self.id),
            callable=schema_registry.__setitem__,
            args=(self.id, schema),
        )


class IFieldInfo(Interface):

    name = NativeStringLine(
        title="The field name",
    )

    title = TextLine(
        title="Title",
        description="A short summary or label",
        default="",
        required=False,
    )

    required = Bool(
        title="Required",
        description="Determines whether a value is required.",
        default=True)

    readonly = Bool(
        title="Read Only",
        description="Can the value be modified?",
        required=False,
        default=False)


class ITextInfo(IFieldInfo):

    min_length = Int(
        title="Minimum length",
        description=(
            "Value after whitespace processing cannot have less than "
            "min_length characters. If min_length is None, there is "
            "no minimum."
        ),
        required=False,
        min=0,  # needs to be a positive number
        default=0)

    max_length = Int(
        title="Maximum length",
        description=(
            "Value after whitespace processing cannot have greater "
            "or equal than max_length characters. If max_length is "
            "None, there is no maximum."
        ),
        required=False,
        min=0,  # needs to be a positive number
        default=None)


def field(context, constructor, name, **kw):

    # Compute the field
    field = constructor(description=context.info.text.strip(), **kw)

    # Save it in the schema's field dictionary
    schema = context.context
    if name in schema.fields:
        raise ValueError("Duplicate field", name)
    schema.fields[name] = field


def textField(context, **kw):
    field(context, Text, **kw)


class IIntInfo(IFieldInfo):

    min = Int(
        title="Start of the range",
        required=False,
        default=None
    )

    max = Int(
        title="End of the range (excluding the value itself)",
        required=False,
        default=None
    )


def intField(context, **kw):
    field(context, Int, **kw)
