
from twisted.application import service
from twisted.application import internet

from nevow import appserver
from nevow import renderer
from nevow import tags
from nevow import formless
from nevow import freeform
import nevow


class IPerson(formless.TypedInterface):
    def act(self, subset = formless.List()):
        pass

    name = formless.String()
    addresses = formless.List(actions=[act])


class USState(formless.Typed):
    def coerce(self, val):
        if len(val) != 2:
            raise formless.InputError, "Doesn't look like a state to me!"
        return val


class ZipCode(formless.FixedDigitInteger):
    def __init__(self, *args, **kw):
        formless.FixedDigitInteger.__init__(self, 5, *args, **kw)


class IAddress(formless.TypedInterface):
    class PropertyGroup(formless.TypedInterface):
        street = formless.String()
        town = formless.String()
        state = USState()
        zip = ZipCode()


class Address(object):
    __implements__ = IAddress,

    street = "foo"
    town = "bar"
    state = "CA"
    zip = 94952

    def __str__(self):
        return "%s %s, %s %s" % (self.street, self.town, self.state, self.zip)


class Person(object):
    __implements__ = IPerson,

    name = "a person's name"

    addresses = [Address(), Address(), Address()]

    def act(self, subset):
        print "SUBSET", subset


class FormPage(renderer.Renderer):
    document = tags.html[
    tags.head[
        tags.link(href="/freeform_css", rel="stylesheet")
    ],
    tags.body[
        "Hello! Here is a form:",
        freeform.configure
    ]
]

    def child_freeform_css(self, request):
        from twisted.python import util
        from twisted.web import static
        return static.File(util.sibpath(nevow.__file__, 'freeform-default.css'))


application = service.Application("formpost5")
internet.TCPServer(
    8080, 
    appserver.NevowSite(
        FormPage(Person())
    )
).setServiceParent(application)
