"""
open/DurusWorks/qp/fill/html.qpy

"""
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, classes=None, **attrs):
    "<"
    tag
    if classes is None:
        classes = []
    else:
        assert type(classes) is list
    if css_class is not None:
        classes = list(classes) + [css_class]
    if classes:
        attrs['class'] = ' '.join(classes)
    for (attr, val) in sorted(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 img:xml(src=None, **kwargs):
    if 'href' in kwargs:
        kwargs['onclick'] = "window.location='%s';" % kwargs.get('href')
    if src:
        htmltag("img", src=src, xml_end=True, **kwargs)
    else:
        htmltag("img", xml_end=True, **kwargs)

def clear_both:xml():
    '\n<div style="clear:both; height:0px; font-size:0px;"></div>\n'

def clear_left:xml():
    '\n<div style="clear:left"></div>\n'

def clear_right:xml():
    '\n<div style="clear:right"></div>\n'

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 element:xml(element_name, args, href=None, pop_id=None, **kwargs):
    assert type(args) is tuple
    if href is not None:
        kwargs['onclick'] = "window.location='%s';" % href
        if 'classes' not in kwargs:
            kwargs['classes'] = ['href']
        else:
            kwargs['classes'] = list(kwargs.get('classes')) + ['href']
        if 'onmouseover' not in kwargs and 'onmouseout' not in kwargs:
            kwargs['onmouseover'] = "if (typeof genlib != 'undefined') genlib.node_add_class(this, 'hovering');"
            kwargs['onmouseout'] = "if (typeof genlib != 'undefined') genlib.node_remove_class(this, 'hovering');"
    if pop_id is not None:
        if 'onmouseover' not in kwargs and 'onmouseout' not in kwargs:
            if href is None:
                kwargs['onmouseover'] = "if (typeof genlib != 'undefined') genlib.display_block('%s');" % pop_id
                kwargs['onmouseout'] = "if (typeof genlib != 'undefined') genlib.display_none('%s');" % pop_id
            else:
                kwargs['onmouseover'] = "if (typeof genlib != 'undefined') {genlib.node_add_class(this, 'hovering'); genlib.display_block('%s')};" % pop_id
                kwargs['onmouseout'] = "if (typeof genlib != 'undefined') {genlib.node_remove_class(this, 'hovering');  genlib.display_none('%s')};" % pop_id

    htmltag(element_name, **kwargs)
    for arg in args:
        arg
    '</%s>' % element_name

def div(*args, **kwargs):
    return element('div', args, **kwargs)

def h1(*args, **kwargs):
    return element('h1', args, **kwargs)

def h2(*args, **kwargs):
    return element('h2', args, **kwargs)

def h3(*args, **kwargs):
    return element('h3', args, **kwargs)

def h4(*args, **kwargs):
    return element('h4', args, **kwargs)

def h5(*args, **kwargs):
    return element('h5', args, **kwargs)

def h6(*args, **kwargs):
    return element('h6', args, **kwargs)

def ol(*args, **kwargs):
    if len(args) == 1 and type(args[0]) is list:
        args = tuple(map(li, args[0]))
    return element('ol', args, **kwargs)

def li(*args, **kwargs):
    return element('li', args, **kwargs)

def ul(*args, **kwargs):
    if len(args) == 1 and type(args[0]) is list:
        args = tuple(map(li, args[0]))
    return element('ul', args, **kwargs)

def dl(*args, **kwargs):
    if len(args) == 1 and type(args[0]) is list:
        args = args[0]
    new_args = []
    for arg in args:
        if isinstance(arg, (tuple, list)) and len(arg) == 2:
            title, description = arg
            if title:
                new_args.append(dt(title))
            if description:
                new_args.append(dd(description))
        else:
            new_args.append(arg)
    return element('dl', tuple(new_args), **kwargs)

def dt(*args, **kwargs):
    return element('dt', args, **kwargs)

def dd(*args, **kwargs):
    return element('dd', args, **kwargs)

def table(*args, **kwargs):
    return element('table', args, **kwargs)    
    
def tr(*args, **kwargs):
    return element('tr', args, **kwargs)        

def th(*args, **kwargs):
    return element('th', args, **kwargs)        

def td(*args, **kwargs):
    return element('td', args, **kwargs)                
    
def tbody(*args, **kwargs):
    return element('tbody', args, **kwargs)                
    
def thead(*args, **kwargs):
    return element('thead', args, **kwargs)                        

def span(*args, **kwargs):
    return element('span', args, **kwargs)

def p(*args, **kwargs):
    return element('p', args, **kwargs)

def pdiv(*args, **kwargs):
    return element('div', args, css_class="p", **kwargs)

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</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>'

genlib_js = None

def get_genlib_js():
    global genlib_js
    if genlib_js is None:
        from os.path import dirname
        genlib_js = open(dirname(__file__) + '/genlib.js').read()
    return genlib_js
