"""rml templatetags"""

import re, os

from django import template
from django.utils.safestring import mark_safe
from django.conf import settings
from rlextra.radxml.xhtml2rml import xhtml2rml
from rldjango.apps.imadj.models import Image

register = template.Library()

def parse_style(style, name):
    """
    Shortcut for parsing style parameters.
    """

    parts = style.split('=')

    if len(parts) > 1:
        name = parts[0].strip()
        value = parts[1].strip()
    else:
        value = parts[0].strip()

    return {name: value}

def tag_xhtml2rml(xhtml, style=None):
    """
    Filer that converts xhtml to rml using rlextra.radxml.xhtml2rml
    Styles can be passed like this:
    xhtml2rml:"xxx, yyyy " -> para style: xxx, table style: yyy
    xhtml2rml:"xxx" -> para style: xxx
    xhtml2rml:"table=yyyy " -> table style: yyy
    xhtml2rml:"para=xxx, table=yyyy " -> para style: xxx, table style: yyy
    """
    styles_dict = {}
    if style:
        style_parts = style.split(',')
        styles_dict.update(
            parse_style(style_parts.pop(0), 'para')
            )
        if style_parts:
            styles_dict.update(
                parse_style(style_parts.pop(0), 'table')
                )
            
    is_text = re.search(ur'^[\w\d\s]+$', xhtml)
    if is_text:
        xhtml = "<p>%s</p>\n" % xhtml
        #.encode('utf8')
    xhtml = xhtml2rml(xhtml)
    if styles_dict.get('para', None):
        xhtml = re.sub('style="normal"', 'style="%s"' % styles_dict['para'], xhtml)
    
    if styles_dict.get('table', None):
        xhtml = re.sub('style="noPaddingStyle"', 'style="%s"' % styles_dict['table'], xhtml)

    return mark_safe(xhtml)

tag_xhtml2rml.is_save = True # pylint: disable-msg=W0612
register.filter('xhtml2rml', tag_xhtml2rml)

def to_rml(obj, context=None):
    """
    Calls to_rml on object passing context
    """
    if type(obj) is dict:
        return mark_safe(obj.get('to_rml', ''))
    if getattr(obj, 'to_rml', None):
        return obj.to_rml(context)
    return ''

to_rml.is_save = True # pylint: disable-msg=W0612
register.filter('to_rml', to_rml)

def list2ntuplets(alist, length=2):
    """
    Creates tuplets of given length from lists.
    """
    tuplets = []
    tuplet = []
    counter = 0
    for item in alist:
        if counter < length:
            tuplet.append(item)
            counter += 1
        else:
            tuplets.append(tuplet)
            counter = 0
            tuplet = []
    if tuplet:
        while length > len(tuplet):
            tuplet.append(None)
        tuplets.append(tuplet)
    return tuplets

register.filter('list2ntuplets', list2ntuplets)

@register.simple_tag
def random_photos():
    """
    Gets a random sample of high_res size photos from the image gallery
    """
    images = Image.objects.filter(tags__id='highres_photo').order_by('?')[:4]
    rml = ''
    for i, image in enumerate(images):
        if i != 0:
            rml += '<nextFrame/>'
        rml += '<imageAndFlowables imageWidth="367" imageHeight="243" imageSide="left" preserveAspectRatio="1" imageRightPadding="10" imageBottomPadding="5" imageName="%s"></imageAndFlowables>' % os.path.join(settings.IMADJ_ROOT, image.id)
    return rml


@register.simple_tag
def random_photos_page_template():
    """
    Gets a random sample of high_res size photos from the image gallery
    """
    images = Image.objects.filter(tags__id='highres_photo').order_by('?')[:3]
    positions = [(433,327.5),(42,101.5),(433,101.5),]
    rml = ''
    for i, image in enumerate(images):
        rml += '<image file="%s" x="%d" y="%d" width="367" height="183.5" preserveAspectRatio="1"/>' % (os.path.join(settings.IMADJ_ROOT, image.id), positions[i][0], positions[i][1])
    return rml


