"""
$URL: svn+ssh://sting.mems-exchange.org/repos/trunk/DurusWorks/qp/fill/html.qpy $
$Id: html.qpy 32701 2010-09-02 14:26:08Z dbinger $
"""
from qpy import xml, stringify, xml_quote
import sys

if sys.version < "3":
    from urllib import quote as url_quote, unquote as url_unquote
else:
    from urllib.parse import quote as url_quote, unquote as url_unquote

url_unquote # Quiet code checker.

def htmltag:xml(tag, xml_end=False, css_class=None, **attrs):
    "<"
    tag
    if css_class is not None:
        attrs['class'] = css_class
    for (attr, val) in attrs.items():
        if val is not None:
            ' %s="%s"' % (attr, val)
    if xml_end:
        " />"
    else:
        ">"

def href:xml(url, text, title=None, **attrs):
    htmltag("a", href=url, title=title, **attrs)
    text
    "</a>"

def dl:xml(tuples, **kwargs):
    htmltag('dl', **kwargs)
    for title, description in tuples:
        if title:
            '<dt>%s</dt>' % title
        if description:
            '<dd>%s</dd>' % description

    '</dl>'

def ul:xml(items, **kwargs):
    htmltag('ul', **kwargs)
    for item in items:
        '<li>%s</li>' % item
    '</ul>'

def ol:xml(items, **kwargs):
    htmltag('ol', **kwargs)
    for item in items:
        '<li>%s</li>' % item
    '</ol>'

def nl2br:xml(v):
    return xml(xml.quote(v).replace("\n", "<br />"))

def nlnl2brbr:xml(v):
    return xml(xml.quote(v).replace("\n\n", "<br /><br />"))

def div:xml(*args, **kwargs):
    htmltag('div', **kwargs)
    for arg in args:
        arg
    '</div>'

def url_with_query(path, **attrs):
    result = xml(url_quote(stringify(path)))
    if attrs:
        result += "?" + xml("&").join([
            url_quote(stringify(key)) + "=" + url_quote(stringify(value))
            for key, value in attrs.items()])
    return result

def javascript:xml(*args):
    '\n<script type="text/javascript"><!--\n'
    for arg in args:
        xml(arg)
    '\n-->\n</script>\n'

def mailto:xml(to, subject=None, body=None):
    '<a class="mailto" href="mailto:'
    xml(xml_quote(to).replace('@', '&#64;'))
    if subject or body:
        '?'
    if subject:
        'Subject='
        url_quote(subject)
        if body:
            '&'
    if body:
        'body='
        url_quote(body)
    '">'
    xml(xml_quote(to).replace('@', '&#64;'))
    '</a>'

