

from tags import *

import random


def rand(context, data):
    return random.randint(0, 200)


def multiply(context, data):
    return data * 5


def sequence(context, data):
    patterns = context.generatePatterns('item')
    return [patterns.next()(data=item) for item in data]


def slotFiller(context, data):
    assert hasattr(data, 'items'), "slotFiller needs an object which returns key, value tuples in response to items."
    for k, v in data.items():
        try:
            slot = context.locateSlots(k).next()
        except StopIteration:
            raise RuntimeError, "Slot %s was not found." % k
        slot.children.append(v)
    context.tag.renderer = None
    return context.tag


def selectOptioner(context, data):
    tag = context.tag.clone(deep=False)
    tag(name="flavor")
    for value, string in data:
        tag[
            option(value=value)[
                string
            ]
        ]
    tag.renderer = None
    return tag


doc = html[
    head[
        title["Hello, World"]
    ],
    body[
        div(
            style="width: 100%; background-color: light-blue;",
            data=rand
        )[
            "Here are some random numbers: ",
            str, " ",
            str, " ",
            str, " ",
        ],
        ul(data={'one': 1, 'two': rand, 'three': 3})[
            li(data=directive("one"), renderer=str),
            li(data=directive("two"), renderer=multiply),
            li(data=directive("three"), renderer=multiply),
        ],
        ol(data=[42, rand, 69])[
            li(data=_2, renderer=multiply),
            li(data=_1, renderer=multiply),
            li(data=_0, renderer=multiply),
            li(data=multiply, renderer=sequence)[
                div(style="border: 1px solid blue; margin-bottom: 0.5em", pattern="item", renderer=str),
                div(style="border: 1px solid red; margin-bottom: 0.5em", pattern="item", renderer=multiply),
            ]
        ],
        table(
            data=[{'name': 'Fred', 'age': 'Old'},
                    {'name': 'Bob', 'age': 'Young'}]
        )[
            tr[
                td["NAME"],
                td["AGE"]
            ],

            div(renderer=sequence)[
                tr(pattern="item", renderer=slotFiller)[
                    td(style="background-color: #efefef", slot="name"),
                    td(style="background-color: #abcdef", slot="age"),
                ]
            ]
        ],
        select(data=[('red', 'Cherry'), ('orange', 'Orange'), ('yellow', 'Banana'), ('blue', 'Grape')],
                renderer=selectOptioner)
    ]
]
