# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - Image Macro

    This macro is used to display an image with the ability to resize 
    and/or provide an alt text for it.

    Syntax:
        [[Image(image_src, [width=width, [height=height], [alt=image_src])]]

    Note: Although providing an alt text is optional please do always provide a sensible,
    descriptive alt text to ease image accessing to people using screenreaders.

    Parameters:
        image_src: image attachment file name or the URL of an image

     Keyword Parameters:    
        width:  rendered image width (optional)
        height: rendered image height (optional)
        alt:    alt text for the image (optional). By default alt is set to
                to image_src, however this does not make much sense for a real
                AccessibleMoin. Please do provide always a sensible, more descriptive
                alt text so that blind people can get a clue, what is shown on the image.
                Compare: "landscape.jpg" vs. "Photo of a typical Scottish landscape showing the
                wideness of the Scottish Highlands".
                If the image is not important for understanding and just there for layout purposes
                please provide in the case an emtpy alt text, so that it is clear to blind people
                that the image is only there for beautification of the page without deeper meaning
                like illustrating something.

    Examples:
        Picture included for beautification only:
         [[Image(pic.png, height=100, alt= )]]
                  
        Pictures conveying some important content:
         [[Image(pic.png, alt=Short description of the image)]]
         [[Image(OtherWikiSite/pic.png, widht=50, alt=Short description of the image)]]
         [[Image(http://webcam.portalmuc.de/images/webcam/webcam_marienplatz.jpg, height=100, alt=Short description of the image)]]

    The Image macro is a simple modification of the ImageLink macro.
    ImageLink macro copyright:
                2001 by Jeff Kunce,
                2004 by Marcin Zalewski,
                2004-2006 by Reimar Bauer (R.Bauer@fz-juelich.de),
                2006 by Thomas Waldmann

    Image macro            
    @copyright: 2007 by Oliver Siemoneit
    @license: GNU GPL, see COPYING for details.

    Changes:
    21.12.06    Parameter values now also take "=None" e.g. "width=None"
    10.02.07    Alt text is set by default to img_src now. 
    25.04.07    Fixed problems that urls with "=" are interpreted as keywords
"""

import os
from MoinMoin import wikiutil, config
from MoinMoin.action import AttachFile

kwAllowed = ['width', 'height', 'alt']

def _is_URL(text):
    """ Answer true if text is an URL.
        The method used here is pretty dumb. Improvements are welcome.
    """
    return '://' in text

def execute(macro, args):
    request = macro.request
    _ = request.getText
    formatter = macro.formatter
    if args:
        args = args.split(',')
        args = [arg.strip() for arg in args]
    else:
        args = []

    argc = len(args)
    kw_count = 0
    kw = {} # create a dictionary for the formatter.image call
    for arg in args :
        if '=' in arg:
            key, value = arg.split('=', 1)
            # avoid that urls with "=" are interpreted as keyword
            if key.lower() not in kwAllowed:
                continue
            if value != 'None':
                kw_count += 1
                kw[str(key.lower())] = wikiutil.escape(value, quote=1)

    argc -= kw_count
    if not argc or argc and not args[0]:
        msg = 'Not enough arguments to Image macro! Calling syntax: [[Image(image_src, [width=width], [height=height], [alt=img_src])]]'
        return "%s%s%s" % (formatter.sysmsg(1), formatter.text(msg), formatter.sysmsg(0))

    image = args[0]
    if _is_URL(image):
        kw['src'] = image
    else:
        pagename, attname = AttachFile.absoluteName(image, formatter.page.page_name)
        kw['src'] = AttachFile.getAttachUrl(pagename, attname, request)
        attachment_fname = AttachFile.getFilename(request, pagename, attname)
        if not os.path.exists(attachment_fname):
            linktext = _('Upload new attachment "%(filename)s"')
            return wikiutil.link_tag(request,
                                     ('%s?action=AttachFile&rename=%s' % (
                                         wikiutil.quoteWikinameURL(pagename),
                                         wikiutil.url_quote_plus(attname))),
                                     linktext % {'filename': attname})
    if not 'alt' in kw:
        kw['alt'] = image

    return "%s" % formatter.image(**kw)    

    
