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

    PURPOSE:
   
       This macro is used to make a link that displays an image (can be given as either attachment or URL) and links to either an URL
       or a wiki page. Optionally the size of the image can be adjusted. If no target is given the link will point to the image
       itself.
    
    CALLING SEQUENCE:
        [[ImageLink(attachment|URL,[WikiName|URL],[width=width,[height=heigt]])]]

    INPUTS:
        attachment:image name of attachment or the URL of 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(München.png,München,height=100)]]
        [[ImageLink(Images/München.png,München,height=100)]]
        [[ImageLink(http://webcam.portalmuc.de/images/webcam/webcam_marienplatz.jpg,München Marienplatz)]]
        [[ImageLink(plot.png,width=200)]]
        [[ImageLink(plot.png,height=200)]]
        [[ImageLink(plot.png)]]
        [[ImageLink(http://webcam.portalmuc.de/images/webcam/webcam_marienplatz.jpg,http://www.muenchen.de,width=150)]]
        [[ImageLink(münchen.png,http://www.muenchen.de,width=50)]]
        [[ImageLink(http://webcam.portalmuc.de/images/webcam/webcam_marienplatz.jpg)]]
        [[ImageLink(example.png,alt=whateveryouwant(üöä))]]

    PROCEDURE:
        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
       Chong-Dae Park:
            2005-04-17 Version 1.3.3-8 code refactored
                       IMG with no alt tag is not recommended in the HTML standard.
                       It keeps user specified alt tag. If it is not, it tries to use WikiName or image name instead.
       Reimar Bauer:
            2005-04-21 Version 1.3.3-9 bug fixed
                       When the image does not exist yet, it gives you a "Upload Image" link, this link does not
                       work. I suspect that this only is a problem on sub-pages, caused by incorrect escaping of
                        "/". -- CraigJohnson

            2005-12-19 Versiom 1.5.0-10 feature added to link to images on different wiki pages
            2006-02-14 Version 1.5.2-11 bug fixed for filename of attached image is Chinese (encode added)
            2006-02-22 Version 1.5.2-12 code refactored

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


def _is_URL(text):
    '''answer true if text is a URL.
    The method used here is pretty dumb. Improvements are welcome.
    jjk  03/28/01'''
    if '://' in text:
        return True

def execute(macro, text):
    kw = {} # create a dictionary for the formatter.image call
    if text:
        arguments = text.split(',')
    else:
        arguments = []

    number_args = len(arguments)
    count = 0
    for arg in arguments:
        if '=' in arg:
            count += 1
            key = arg.split('=')
            kw[str(key[0])] = ''.join(key[1])
            
    number_args = number_args - count

    if number_args < 1:
        msg='Not enough arguments to ImageLink macro! e.g. [[ImageLink(example.png,WikiName,width=200)]].'
        return "%s%s%s" % (macro.formatter.sysmsg(1),
                           macro.formatter.text(msg),
                           macro.formatter.sysmsg(0))

    attname = arguments[0]
    
    if number_args >= 2:
        wikiname = arguments[1]
        
    if attname.find('/') > -1 and attname.find(':') == -1:
        current_pagename, attname = attname.split('/') 
    else:
        current_pagename = macro.formatter.page.page_name    

    if _is_URL(arguments[0]):
        kw['src'] = arguments[0]
    else:
        kw['src'] = AttachFile.getAttachUrl(current_pagename,attname,macro.request)
        attachment_path = os.path.join(AttachFile.getAttachDir(macro.request,current_pagename), attname).encode(config.charset)

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

    if not kw.has_key('alt'):
        if number_args == 1 or _is_URL(arguments[1]):
            if _is_URL(arguments[0]):
                # Get image name http://here.com/dir/image.png -> image.png
                kw['alt'] = wikiutil.taintfilename(macro.formatter.text(arguments[0].split('/')[-1]))
                kw['alt'] = arguments[0].split('/')[-1]
            else:
                kw['alt'] = attname
        else:
            kw['alt'] = wikiname

    if number_args == 1:
        return "%s%s%s" % (macro.formatter.url(1,kw['src']),
                           macro.formatter.image(**kw),
                           macro.formatter.url(0))

    if number_args == 2:
        if _is_URL(arguments[1]):
            return "%s%s%s" % (macro.formatter.url(1,arguments[1]),
                               macro.formatter.image(**kw),
                               macro.formatter.url(0))
        else:
            return "%s%s%s" % (macro.formatter.pagelink(1,wikiname),
                               macro.formatter.image(**kw),
                               macro.formatter.url(0))

