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

    PURPOSE:
        This macro is used to set a link as WikiName for an attached image. Optional the size of the
         image could be adjusted. If no WikiName is given the attachment is linked to the image itselfs.

    CALLING SEQUENCE:
        [[ImageLink(attachment|URL,[WikiName|URL],[width=width,[height=heigt]])]]

    INPUTS:
        attachment:image name of attachment or the URL to an image

    OPTIONAL INPUTS:
        WikiName: the page to set the link to or the URL to link to


    KEYWORD PARAMETERS:
        width: width of the embedded image
        height: height of the embedded image

    EXAMPLE:
        [[ImageLink(plot.png,FrontPage,width=20,height=20)]]
        [[ImageLink(plot.png,FrontPage,height=20)]]
        [[ImageLink(plot.png,FrontPage)]]
        [[ImageLink(plot.png,width=20,height=20)]]
        [[ImageLink(plot.png,width=20)]]
        [[ImageLink(plot.png)]]
        [[ImageLink(http://localhost/wiki/modern/img/to_slide.png,http://localhost/StartSeite,width=50)]]
        [[ImageLink(http://localhost/wiki/modern/img/to_slide.png,FrontPage,width=50)]]
        [[ImageLink(plot.png,http://localhost/StartSeite,width=50)]]
        [[ImageLink(http://localhost/wiki/modern/img/to_slide.png)]]
        [[ImageLink(http://localhost/wiki/modern/img/to_slide.png,alt=whateveryouwant)]]

    PROCEDURE:
        This routine requires attachment enabled. If the attachment isn't downloaded at all
         the attachment line is shown.
         If you give only one image size argument e.g. width only the other one is calculated

        It must be in "MoinMoin/macro"

        Please remove the version number from the file name!

        From JeffKunce ImageLink.py I have copied _is_URL to this routine. I have no better idea too.

    HISTORY:
      The first published version on MoinMoin I know of ImageLink was written by JeffKunce in 2001.

    MODIFICATION HISTORY:
        @copyright: 2004 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.

    Marcin Zalewski:
        Some things that were causing problems on my wiki are changed
            (wikiutil.link_tag and macro.formatter.pagelink implemented)

        Marcin Zalewski:
            Added title attribute to the created link. One could generalize that to
            add arbitrary attributes.

            One could also add class attributes to <a> and/or
            <img> elements. I do not see the need for such modifications. If however this is
            to be done in the future one would need to add 'html_class' key to the kw dictionary
            with a corresponding value to add class to <img> element. To add class to <a> element
            one needs to add 'css_class' key with a corresponding value to the dictionary passed to
            pagelink call.
       Reimar Bauer:
            2004-12-23 Adopted to MoinMoin Version 1.3.1-1
            2004-12-23 SYNTAX CHANGE Version 1.3.1-2
                   width and height and probably other keywords must be called as keywords (e.g. height=20)
            2004-12-31 Version 1.3.1-3 code clean up
            2005-01-16 Bug fixed in the errorhandler found and patch code from Malte Helmert
	    2005-03-05 Version 1.3.3-5 Bug fixed found by cypress
	                               ''If I put [[ImageLink(moinmoin.png)]] it bombs''
            2005-03-28 Version 1.3.3-6 feature request added by CDPark:
                        ''Can we use an external image? And an external target? ''
            2005-04-16 Version 1.3.3-7 no default alt tag definition requested by  CDPark and AlexanderSchremmer


"""

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

def _is_URL(aString):
    '''answer true if aString is a URL.
    The method used here is pretty dumb. Improvements are welcome.
    jjk  03/28/01'''
    return string.find(aString, '://')>0


def execute(macro, text):

    kw ={} # create a dictionary for the formatter.image call

    if text:
        args=text.split(',')
    else:
        args=[]

    number_args=len(args)
    count=0
    for a in args :
        if (a.find('=') > -1):
            count=count+1
            key=a.split('=')
            kw[str(key[0])]=wikiutil.escape(string.join(key[1],''), quote=1)

    number_args=number_args-count

    if (number_args < 1):
        msg='Not enough arguments to ImageLink macro! Try [[ImageLink(attachment,[WikiName],[width=width,[height=heigt]])]]'
        return macro.formatter.sysmsg(1)+macro.formatter.text(msg)+ macro.formatter.sysmsg(0)


    attname=wikiutil.taintfilename(macro.formatter.text(args[0]))
    if (number_args == 2) :
        wikiname=args[1]
    current_pagename=macro.formatter.page.page_name
    kw['src']=AttachFile.getAttachUrl(current_pagename,attname,macro.request)
    attachment_path = os.path.join(AttachFile.getAttachDir(macro.request,current_pagename), attname)


    if not _is_URL(args[0]):

        if not os.path.exists(attachment_path):
            import urllib
            linktext = macro.request.getText('Upload new attachment "%(filename)s"')
            return wikiutil.link_tag(macro.request,
                                 '%s?action=AttachFile&amp;rename=%s' %
                                 (wikiutil.quoteWikinameFS(current_pagename),
                                 urllib.quote_plus(attname)),
                                 linktext % {'filename': attname})

    if (number_args == 1):
        if _is_URL(args[0]):
           kw['src']=args[0]
           image_link=macro.formatter.image(**kw)
           return macro.formatter.url(1,kw['src'] )+image_link +macro.formatter.url(0)
        else:
            kw['title']=attname
            image_link=macro.formatter.image(**kw)
            return macro.formatter.url(1,kw['src'] )+image_link +macro.formatter.url(0)

    if (number_args == 2 ):
        if _is_URL(args[0]):
            kw['src']=args[0]
        else:
            kw['title']=wikiname

        image_link=macro.formatter.image(**kw)
        if _is_URL(args[1]):
           kw['src']=args[1]
           return macro.formatter.url(1,kw['src'] )+image_link+macro.formatter.url(0)
        else:
           return macro.formatter.pagelink(1,wikiname)+image_link+macro.formatter.url(0)

