"""$URL: svn+ssh://svn/repos/trunk/quixote/form2/widget.py $
$Id: widget.py 23260 2003-12-03 11:29:53Z dbinger $

Provides the basic web widget classes: Widget itself, plus StringWidget,
TextWidget, CheckboxWidget, etc.
"""

import struct
from types import FloatType, IntType, ListType, StringType, TupleType
from quixote import get_request
from quixote.html import htmltext, htmlescape, htmltag, ValuelessAttr
from quixote.upload import Upload

try:
    True, False
except NameError:
    True = 1
    False = 0


def subname(prefix, name):
    """Create a unique name for a sub-widget or sub-component."""
    # $ is nice because it's valid as part of a Javascript identifier
    return "%s$%s" % (prefix, name)


def merge_attrs(base, overrides):
    """({string: any}, {string: any}) -> {string: any}
    """
    items = []
    if base:
        items.extend(base.items())
    if overrides:
        items.extend(overrides.items())
    attrs = {}
    for name, val in items:
        if name.endswith('_'):
            name = name[:-1]
        attrs[name] = val
    return attrs
    

class Widget:
    """Abstract base class for web widgets.

    Instance attributes:
      name : string
      value : any
      error : string
      attrs : {string: any}

    Feel free to access these directly; to set them, use the 'set_*()'
    modifier methods.
    """

    def __init__(self, name, value=None, attrs=None, **kwattrs):
        assert self.__class__ is not Widget, "abstract class"
        self.name = name
        self.error = None
        self.attrs = merge_attrs(attrs, kwattrs)
        request = get_request()
        if request.form:
            self._parse(request)
        else:
            self.set_value(value)
        
    def __repr__(self):
        return "<%s at %x: %s>" % (self.__class__.__name__,
                                   id(self),
                                   self.name)

    def __str__(self):
        return "%s: %s" % (self.__class__.__name__, self.name)

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_value(self):
        return self.value

    def set_value(self, value):
        self.value = value

    def set_error(self, error):
        self.error = error

    def get_error(self):
        return self.error

    def _parse(self, request):
        # subclasses may override but this is not part of the public API
        value = request.form.get(self.name)
        if type(value) is StringType and value.strip():
            self.value = value
        else:
            self.value = None

    def render(self):
        """render() -> HTML text"""
        raise NotImplementedError, 'subclass must implement'


# class Widget

# -- Fundamental widget types ------------------------------------------
# These correspond to the standard types of input tag in HTML:
#   text     StringWidget
#   password PasswordWidget
#   radio    RadiobuttonsWidget
#   checkbox CheckboxWidget
#
# and also to the other basic form elements:
#   <textarea>  TextWidget
#   <select>    SingleSelectWidget
#   <select multiple>
#               MultipleSelectWidget

class StringWidget(Widget):
    """Widget for entering a single string: corresponds to
    '<input type="text">' in HTML.

    Instance attributes:
      value : string
    """

    # This lets PasswordWidget be a trivial subclass
    HTML_TYPE = "text"

    def render(self):
        return htmltag("input", xml_end=True,
                       type=self.HTML_TYPE,
                       name=self.name,
                       value=self.value,
                       **self.attrs)


class FileWidget(StringWidget):
    """Subclass of StringWidget for uploading files.

    Instance attributes: none
    """

    HTML_TYPE = "file"

    def _parse(self, request):
        parsed_value = request.form.get(self.name)
        if isinstance(parsed_value, Upload):
            self.value = parsed_value
        else:
            self.value = None


class PasswordWidget(StringWidget):
    """Trivial subclass of StringWidget for entering passwords (different
    widget type because HTML does it that way).

    Instance attributes: none
    """

    HTML_TYPE = "password"


class TextWidget(Widget):
    """Widget for entering a long, multi-line string; corresponds to
    the HTML "<textarea>" tag.

    Instance attributes:
      value : string
    """

    def _parse(self, request):
        Widget._parse(self, request)
        if self.value and self.value.find("\r\n") >= 0:
            self.value = self.value.replace("\r\n", "\n")

    def render(self):
        return (htmltag("textarea", name=self.name, **self.attrs) +
                htmlescape(self.value or "") +
                htmltext("</textarea>"))


class CheckboxWidget(Widget):
    """Widget for a single checkbox: corresponds to "<input
    type=checkbox>".  Do not put multiple CheckboxWidgets with the same
    name in the same form.

    Instance attributes:
      value : boolean
    """

    def _parse(self, request):
        self.value = request.form.has_key(self.name)

    def render(self):
        return htmltag("input", xml_end=True,
                       type="checkbox",
                       name=self.name,
                       value="yes",
                       checked=self.value and ValuelessAttr or None,
                       **self.attrs)



class SelectWidget(Widget):
    """Widget for single or multiple selection; corresponds to
    <select name=...>
      <option value="Foo">Foo</option>
      ...
    </select>

    Instance attributes:
      options : [ (value:any, description:any, key:string) ]
      value : any
        The value is None or an element of dict(options.values()).
    """

    def __init__(self, name, value=None, options=None, sort=True,
                 verify_selection=True, attrs=None, **kwattrs):
        assert self.__class__ is not SelectWidget, "abstract class"
        self.options = []
        if options is not None:
            assert options, 'cannot pass empty options list'
            self.set_options(options, sort)
        self.verify_selection = verify_selection
        Widget.__init__(self, name, value, attrs=attrs, **kwattrs)

    def get_allowed_values(self):
        return [item[0] for item in self.options]

    def get_descriptions(self):
        return [item[1] for item in self.options]

    def set_value(self, value):
        self.value = None
        for object, description, key in self.options:
            if value == object:
                self.value = value
                break

    def _generate_keys(self, values, descriptions):
        """Called if no keys were provided.  Try to generate a set of keys
        that will be consistent between rendering and parsing.
        """
        # try to use ZODB object IDs
        keys = []
        for value in values:
            if value is None:
                oid = ""
            else:
                oid = getattr(value, "_p_oid", None)
                if not oid:
                    break
                hi, lo = struct.unpack(">LL", oid)
                oid = "%x" % ((hi << 32) | lo)
            keys.append(oid)
        else:
            # found OID for every value
            return keys
        # can't use OIDs, try using descriptions
        used_keys = {}
        keys = map(str, descriptions)
        for key in keys:
            if used_keys.has_key(key):
                raise ValueError, "duplicated descriptions (provide keys)"
            used_keys[key] = 1
        return keys

    def set_options(self, options, sort=False):
        """(options: [objects:any], sort=False)
         or
           (options: [(object:any, description:any)], sort=False)
         or
           (options: [(object:any, description:any, key:any)], sort=False)
        """

        """
        Set the options list.  The list of options can be a list of objects, in
        which case the descriptions default to map(htmlescape, objects)
        applying htmlescape() to each description and
        key.
        If keys are provided they must be distinct.  If the sort keyword
        argument is true, sort the options by case-insensitive lexicographic
        order of descriptions, except that options with value None appear
        before others.
        """
        if options:
            first = options[0]
            values = []
            descriptions = []
            keys = []
            if type(first) is TupleType:
                if len(first) == 2:
                    for value, description in options:
                        values.append(value)
                        descriptions.append(description)
                elif len(first) == 3:
                    for value, description, key in options:
                        values.append(value)
                        descriptions.append(description)
                        keys.append(str(key))
                else:
                    raise ValueError, 'invalid options %r' % options
            else:
                values = descriptions = options

            if not keys:
                keys = self._generate_keys(values, descriptions)

            options = zip(values, descriptions, keys)

            if sort:
                def make_sort_key(option):
                    value, description, key = option
                    if value is None:
                        return ('', option)
                    else:
                        return (str(description).lower(), option)
                doptions = map(make_sort_key, options)
                doptions.sort()
                options = [item[1] for item in doptions]
        self.options = options

    def _parse_single_selection(self, parsed_key):
        for value, description, key in self.options:
            if key == parsed_key:
                return value
        else:
            if self.verify_selection:
                self.error = "invalid value selected"
                return None
            elif self.options:
                return self.options[0][0]
            else:
                return None

    def set_allowed_values(self, allowed_values, descriptions=None,
                           sort=False):
        """(allowed_values:[any], descriptions:[any], sort:boolean=False)

        Set the options for this widget.  The allowed_values and descriptions
        parameters must be sequences of the same length.  The sort option
        causes the options to be sorted using case-insensitive lexicographic
        order of descriptions, except that options with value None appear
        before others.
        """
        if descriptions is None:
            self.set_options(allowed_values, sort)
        else:
            assert len(descriptions) == len(allowed_values)
            self.set_options(zip(allowed_values, descriptions), sort)

    def is_selected(self, value):
        return value == self.value

    def render(self):
        tags = [htmltag("select", name=self.name, **self.attrs)]
        for object, description, key in self.options:
            if self.is_selected(object):
                selected = ValuelessAttr
            else:
                selected = None
            if description is None:
                description = ""
            r = htmltag("option", value=key, selected=selected)
            tags.append(r + htmlescape(description) + htmltext('</option>'))
        tags.append(htmltext("</select>"))
        return htmltext("\n").join(tags)


class SingleSelectWidget(SelectWidget):
    """Widget for single selection.
    """

    SELECT_TYPE = "single_select"

    def _parse(self, request):
        parsed_key = request.form.get(self.name)
        if parsed_key:
            if type(parsed_key) is ListType:
                self.error = "cannot select multiple values"
            else:
                self.value = self._parse_single_selection(parsed_key)
        else:
            self.value = None


class RadiobuttonsWidget(SingleSelectWidget):
    """Widget for a *set* of related radiobuttons -- all have the
    same name, but different values (and only one of those values
    is returned by the whole group).

    Instance attributes:
      delim : string = None
        string to emit between each radiobutton in the group.  If
        None, a single newline is emitted.
    """

    SELECT_TYPE = "radiobuttons"

    def __init__(self, name, value=None,
                 options=None,
                 delim=None, attrs=None, **kwattrs):
        SingleSelectWidget.__init__(self, name, value, options,
                                    attrs=attrs, **kwattrs)
        if delim is None:
            self.delim = "\n"
        else:
            self.delim = delim

    def render(self):
        tags = []
        for object, description, key in self.options:
            if self.is_selected(object):
                checked = ValuelessAttr
            else:
                checked = None
            r = htmltag("input",
                        type="radio",
                        name=self.name,
                        value=key,
                        checked=checked,
                        **self.attrs)
            tags.append(r + htmlescape(description) + htmltext('</input>'))
        return htmlescape(self.delim).join(tags)


class MultipleSelectWidget(SelectWidget):
    """Widget for multiple selection.

    Instance attributes:
      value : [any]
        for multipe selects, the value is None or a list of
        elements from dict(self.options).values()
    """

    SELECT_TYPE = "multiple_select"

    def __init__(self, name, value=None, options=None, **kwargs):
        SelectWidget.__init__(self, name, value, options,
                              multiple='multiple', **kwargs)

    def set_value(self, value):
        allowed_values = self.get_allowed_values()
        if value in allowed_values:
            self.value = [ value ]
        elif type(value) in (ListType, TupleType):
            self.value = [ element
                           for element in value
                           if element in allowed_values ] or None
        else:
            self.value = None

    def is_selected(self, value):
        if self.value is None:
            return value is None
        else:
            return value in self.value

    def _parse(self, request):
        parsed_keys = request.form.get(self.name)
        if parsed_keys:
            if type(parsed_keys) is ListType:
                self.value =  [value
                               for value, description, key in self.options
                               if key in parsed_keys] or None
            else:
                self.value = [self._parse_single_selection(parsed_keys)]
        else:
            self.value = None


class ButtonWidget(Widget):
    """
    Instance attributes:
      label : string
      value : boolean
    """

    HTML_TYPE = "button"

    def __init__(self, name, value=None, attrs=None, **kwattrs):
        self.name = name
        self.error = None
        self.attrs = merge_attrs(attrs, kwattrs)
        # slightly different behavior here, we always render the
        # tag using the 'value' passed in as a parameter.  The 'value'
        # attribute is a boolean that is true if the button's name appears
        # in the request.
        self.label = value
        request = get_request()
        if request.form:
            self._parse(request)
        else:
            self.value = False

    def set_error(self, error):
        return TypeError, 'error not allowed on submit buttons'

    def render(self):
        value = (self.label and htmlescape(self.label) or None)
        return htmltag("input", xml_end=True, type=self.HTML_TYPE,
                       name=self.name, value=value, **self.attrs)

    def _parse(self, request):
        self.value = request.form.has_key(self.name)


class ResetWidget(ButtonWidget):
    HTML_TYPE = "reset"


class SubmitWidget(ButtonWidget):
    HTML_TYPE = "submit"


class HiddenWidget(Widget):
    """
    Instance attributes:
      value : string
    """

    def set_error(self, error):
        return TypeError, 'error not allowed on hidden widgets'

    def render(self):
        if self.value is None:
            value = None
        else:
            value = htmlescape(self.value)
        return htmltag("input", xml_end=True,
                       type="hidden",
                       name=self.name,
                       value=value,
                       **self.attrs)


# -- Derived widget types ----------------------------------------------
# (these don't correspond to fundamental widget types in HTML,
# so they're separated)

class NumberWidget(StringWidget):
    """
    Instance attributes: none
    """

    # Parameterize the number type (either float or int) through
    # these class attributes:
    TYPE_OBJECT = None                  # eg. int, float
    TYPE_ERROR = None                   # human-readable error message
    TYPE_CONVERTER = None               # eg. int(), float()

    def __init__(self, name, value=None, attrs=None, **kwattrs):
        assert self.__class__ is not NumberWidget, "abstract class"
        assert value is None or type(value) is self.TYPE_OBJECT, (
            "form value '%s' not a %s: got %r" % (name,
                                                  self.TYPE_OBJECT,
                                                  value))
        StringWidget.__init__(self, name, value, attrs=attrs, **kwattrs)

    def _parse(self, request):
        StringWidget._parse(self, request)
        if self.value is not None:
            try:
                self.value = self.TYPE_CONVERTER(self.value)
            except ValueError:
                self.error = self.TYPE_ERROR


class FloatWidget(NumberWidget):
    """
    Instance attributes:
      value : float
    """
    TYPE_OBJECT = FloatType
    TYPE_CONVERTER = float
    TYPE_ERROR = "must be a number"


class IntWidget(NumberWidget):
    """
    Instance attributes:
      value : int
    """
    TYPE_OBJECT = IntType
    TYPE_CONVERTER = int
    TYPE_ERROR = "must be an integer"


class OptionSelectWidget(SingleSelectWidget):
    """Widget for single selection with automatic submission and early
    parsing.  This widget parses the request when it is created.  This
    allows its value to be used to decide what other widgets need to be
    created in a form.  It's a powerful feature but it can be hard to
    understand what's going on.

    Instance attributes:
      value : any
    """

    SELECT_TYPE = "option_select"

    def __init__(self, name, value=None, options=None, **kwargs):
        SingleSelectWidget.__init__(self, name, value, options,
                                    onchange='submit()', **kwargs)

    def render(self):
        return (SingleSelectWidget.render(self) +
                htmltext('<noscript>'
                         '<input type="submit" name="" value="apply" />'
                         '</noscript>'))

