# -*- coding: utf-8 -*-
"""
    MoinMoin - NewWindow Macro

    PURPOSE:
        This macro is used to create a link which opens in a new browser window

    CALLING SEQUENCE:
        [[NewWindow(target,[description],[link attributes])]]

    INPUTS:
        target: the target to link to (external link or pagename)
        description: the name for the link
        link attributes: normal html attributes for the link (like title='')

    EXAMPLE:
        [[NewWindow("FrontPage","to FrontPage",title="open FrontPage in new window")]]
        [[NewWindow(http://thor,Thor,style="background-color:yellow")]]
        [[NewWindow(http://thor,Thor)]]
        [[NewWindow(http://www.google.com)]]

    MODIFICATION HISTORY:
        @copyright: 2005 by Mat (mat AT matware DOT de)
        @license: GNU GPL, see COPYING for details.
"""

from MoinMoin import wikiutil, util
def execute(macro, text):
    if text:
        args = text.split(',')
    else:
        msg =  'Usage: [[NewWindow(link, linktext, [attributes])]]'
        return macro.formatter.sysmsg(1) + macro.formatter.text(msg) + macro.formatter.sysmsg(0)

    numberOfArgs = len(args)
    href = args[0].replace('"','').strip('')

    if numberOfArgs > 1:
        text = args[1].replace('"','').strip('')
    else:
        text = href

    if numberOfArgs > 2:
        attribs = ''
        for a in args[2:]:
            a = a.split('=')
            a[1] = a[1].replace('"','')

            attribs = '%s %s="%s"' % (attribs, a[0], a[1])
    else:
        attribs = ''

    if href.startswith('http://') or href.startswith('https://') or href.startswith('ftp://'):
        # external link
        html = '''<a href="%(href)s" target="_blank"%(attribs)s>%(img)s</a>&nbsp;<a href="%(href)s" target="_blank"%(attribs)s>%(text)s</a>''' % {
            'img':     util.web.getLinkIcon(macro.request, macro.formatter, "www"),
            'href':    href,
            'attribs': attribs,
            'text':    text,
        }
    else:
        # wiki link
        html = '<a href="%(href)s" target="_blank"%(attribs)s>%(text)s</a>' % {
            'href':    macro.request.getScriptname() + '/' + wikiutil.quoteWikinameURL(href),
            'attribs': attribs,
            'text':    text,
        }

    return html
