# Copyright (C) 2010 Appropriate Solutions, Inc., all rights reserved.
# This code is released to be used under the terms of the Apache license, by
# Bill Freeman, for Appropriate Solutions, Inc., www.appropriatesolutions.com

from django import template
from django.utils.html import conditional_escape
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
import django.forms

# NOTE: This code takes advantage of django internal interfaces.
# Such are subject to change in new django versions, making this
# code invalid.  It was developed and tested for a Django 1.0.3
# (pinax) based site.  I make no presentation that this stuff
# will work on any other version, or even this version with a
# different set of apps or versions.  But it should be close.
# Your milage may vary.

register = template.Library()

class _PseudoCheckboxBoundField(object):
    """An object from which to render one checkbox.

    Helper class.

    Because the checkbox iterator needs to be able return something
    that acts, closely enough, like a checkbox bound field.
    """
    def __init__(self, name, option_label, option_value, attrs, checked):
        self.parent_name = name
        self.name = option_label
        self.value = option_value
        self.attrs = attrs
        self.checked = checked
        self.id = attrs.get('id', '')
        self.errors = u'' # We don't have individual cb errors

    def tag(self):
        cb = django.forms.CheckboxInput(self.attrs,
                                        check_test=lambda v: self.checked)
        return cb.render(self.parent_name, self.value)

    def label_head(self):
        id = self.id
        if not id:
            return u'<label>'
        return mark_safe(u'<label for="%s">' % id)

    def labeled(self):
        return mark_safe(u'%s%s %s</label>' % (
            self.label_head(),
            self.tag(),
            self.name
            ))

    def lone_label(self):
        return mark_safe(u'%s%s</label>' % (
            self.label_head(),
            self.name
            ))

    def __unicode__(self):
        return self.labeled()

class _ValueGrabber(object):
    """A pseudo widget to capture information from the MultiSelect object.

    This is a helper class.

    There's no clean way to reach into the MultiSelect bound field to
    get this information, but it does call its widget with all the
    necessary info.  This probably has legs because changing the
    render interface would have far reaching consequences.
    """
    def __init__(self):
        self.attrs = {}

    def render(self, name, data, attrs):
        self.name = name
        self.data = data
        self.attrs = attrs

@register.filter
def checkboxiterator(bound_field):
    """Filter the bound field of a multi-select into an iterator of checkboxes.

    Passing the multiselect into the filter gives us access to the bound
    field here.

    We then actually behave as a generator of _PseudoCheckboxBoundField
    objects, which is iterable.
    """
    widget = bound_field.field.widget
    # Snag the bound field details.  Let it's as_widget method do the work.
    bfd = _ValueGrabber()
    bound_field.as_widget(bfd)
    name = bfd.name
    values = bfd.data
    attrs = bfd.attrs

    # Fix up data and attrs
    if values is None:
        values = set()
    else:
        values = set([force_unicode(v) for v in values])
    id = attrs and attrs.get('id', False)
    partial_attrs = widget.build_attrs(attrs, name=name)

    for i, (option_value, option_label) in enumerate(widget.choices):
        option_value = force_unicode(option_value)
        final_attrs = partial_attrs
        if id is not False:
            final_attrs = dict(partial_attrs,
                               id=u'%s_%s' % (id, i))
        yield _PseudoCheckboxBoundField(
            name,
            conditional_escape(force_unicode(option_label)),
            option_value,
            final_attrs,
            option_value in values)
