#!/usr/bin/python
# filename: pseudo_markdown.py

import re
import blogofile_bf as bf

def run(content):
    """Return processed 'unofficial' Markdown pattern that allows to add any
       HTML attributes and attribute values on any elements that can use
       Markdown's title attribute.

       Formats:
           "title !|attribute='value'|"
           "title !|attribute='value', attribute='value'|"
           "!|attribute='value'|"
           "!|attribute='value', attribute='value'|"

       Examples:
           Adding a width and height on <img />:
           * Inline:
               ![alt](/img/logo.png "title !|width='150', height='150'|")
           * Referenced:
               ![alt][id]
               [id]: /img/logo.png "title !|width='150', height='150'|"
    """

    enabled = bf.config.filters.pseudo_markdown.enabled
    titles = re.findall(r'title=(".+?")', content)
    pattern = '!\|.+?\|'

    for title in titles:
        old_attr = title
        new_attr = ''
        if re.search(r'%s' % pattern, old_attr):
            title = re.sub(r'%s|^"|\s*"$' % pattern, '', old_attr).strip()
            attr = re.sub(r'^.+?!\||\|.+?', '', old_attr)
            attrs = attr.replace('\'', '"')
            attrs = ' '.join(attrs.split(','))
            new_attr = '"%s" %s' % (title, attrs)
            content = content.replace(old_attr, new_attr)

    # Remove title attributes with empty values
    empty_titles = re.findall(r'<.+?title="".+?>', content)
    for empty_title in empty_titles:
        content = content.replace('title=""', '')

    return content
