"""
open/DurusWorks/proto/lib/ui/forms.qpy

"""
from qp.fill.css import BASIC_FORM_CSS
from qp.fill.directory import Directory
from qp.fill.form import Form
from qp.fill.widget import CheckboxWidget, FileWidget, MultipleSelectWidget
from qp.fill.widget import RadiobuttonsWidget, SingleSelectWidget
from qp.fill.widget import StringWidget, PasswordWidget
from qp.pub.common import header, footer, page, redirect
import time


class Topping:

    def __init__(self, name, cost):
        self.name = name
        self.cost = cost # in cents

    def __str__(self):
        return "%s: $%.2f" % (self.name, self.cost/100.)


TOPPINGS = [Topping('cheese', 50),
            Topping('pepperoni', 110),
            Topping('green peppers', 75),
            Topping('mushrooms', 90),
            Topping('sausage', 100),
            Topping('anchovies', 30),
            Topping('onions', 25)]

SIZES = [('tiny', 'Tiny (4")'),
         ('small', 'Small (6")'),
         ('medium', 'Medium (10")'),
         ('large', 'Large (14")'),
         ('enormous', 'Enormous (18")')]

class FormsDirectory (Directory):
    """
    a basic form demo.
    """

    def get_exports(self):
        yield '', 'index', 'Forms Demo', None

    def index:xml(self):
        form = Form(enctype="multipart/form-data") # enctype for file upload
        form.add(StringWidget, "name", title="Your Name",
            size=20, required=True)
        form.add(PasswordWidget, "password", title="Password",
            size=20, maxlength=20, required=True)
        form.add(CheckboxWidget, "confirm",
            title="Are you sure?")
        form.add(RadiobuttonsWidget, "color", title="Eye color",
            options=['green', 'blue', 'brown', 'other'])
        form.add(SingleSelectWidget, "size", title="Size of pizza",
            value='medium', options=SIZES)
        # select widgets can use any type of object, no just strings
        form.add(MultipleSelectWidget, "toppings", title="Pizza Toppings",
            value=[TOPPINGS[0]],
            options=TOPPINGS,
            size=5)
        form.add(FileWidget, "file", title="Your Pizza Specification")
        form.add_hidden('time', value=time.time())
        form.add_submit("go", "Go!")
        form.add_submit("stop", "Stop!")
        form.add_submit("cancel", "Cancel")
        if form.get('cancel'):
            redirect('..')

        if not form.is_submitted() or form.has_errors():
            return page('Form Demo', form.render(), style=BASIC_FORM_CSS)

        # Could to more error checking, set errors and return rendered page.

        # The data has been submitted and verified.  Do something interesting
        # with it (save it in DB, send email, etc.).  We'll just display it.
        header('Form Demo: Success', style="th, td { background: #ddd}")
        '<h2>Form data:</h2>'
        '<table style="background: #eee">'
        '<tr>'
        '<th align=left>Name</th>'
        '<th align=left>Type</th>'
        '<th align=left>Value</th>'
        '</tr>'
        for widget in form.get_all_widgets():
            value = widget.parse()
            '<tr>'
            '<td>%s</td>' % widget.get_name()
            '<td>%s</td>' % getattr(value, str('__class__'),
                                      type(value)).__name__
            '<td>'
            if value is None:
                "<i>None</i>"
            elif isinstance(widget, FileWidget):
                repr(value)
                ' (%s bytes)' % len(value.fp.read())
            else:
                repr(value)
            '</td>'
            '</tr>'
        '</table>'
        footer()
