# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - FreeMind browser Macro

    Inserts the FreeMindBrowser applet.
    See http://freemind.sourceforge.net/wiki/index.php/Main_Page

    [[FreeMindBrowser( urlOfMindmap )]]
        displays the FreeMind mindmap specified by urlOfMindmap in the FreeMind browser applet
        there is a default for the width and height of the applet

    [[FreeMindBrowser( urlOfMindmap, width )]]
        displays the FreeMind mindmap specified by urlOfMindmap in the FreeMind browser applet
        the width is taken from the argument list
        there is a default for the height of the applet

    [[FreeMindBrowser( urlOfMindmap, width, height )]]
        displays the FreeMind mindmap specified by urlOfMindmap in the FreeMind browser applet
        the width and height are taken from the argument list


    @copyright: 2005 by Jürgen Lind <xxx@xxx>
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin.action import AttachFile

Dependencies = []

debug = False

# # # # # # # # # # # # # # #
# FMBMacro class
# # # # # # # # # # # # # # #
"""
    Class FMBMacro implements the execution of a FreeMindBrowser macro call.
    One instance must be used per execution.
"""
class FMBMacro:

    appletClass = 'freemind.main.FreeMindApplet.class'
    widthDefault = '100%'
    heightDefault= '500'


    """
        Construct the FMBMacro with the execution arguments.
    """
    def __init__(self, macro, args):
        self.macro = macro
        self.args = args

        # Check and set, if we have an HTML formatter
        self.isHTML = '<br />\n' == self.macro.formatter.linebreak(0)

        appletArchive= "%s/applets/FreeMindBrowser/freemindbrowser.jar" % (self.macro.request.cfg.url_prefix)
        self.appletArchive = self.macro.request.getQualifiedURL( appletArchive )

        self.isFatal = False
        self.applet = [] # this is for the applet code
        self.messages = [] # this is for extra messages


    def execute( self ):
        self.info( "Yippieh - FMBMacro is executing!" )
        self.checkArguments()
        self.computeResult()
        return self.result


    """
        Check the arguments given with the macro call.
    """
    def checkArguments(self):

        if not self.args:
            self.fatal( "At least one argument, i.e. the URL for the mindmap is expected!" )
            self.usage()
        else:
            argsList = self.args.split(',')
            argsLen = len(argsList)

        self.width = FMBMacro.widthDefault
        self.height = FMBMacro.heightDefault

        mindmap = argsList[0].strip()

        if 2 <= argsLen:
            self.width = argsList[1].strip()

        if 3 <= argsLen:
            self.height = argsList[2].strip()

        if 3 < argsLen:
            self.warning( "Too many arguments!" )
            self.usage()

        self.mindmapUrl = self.getMindmapURL(mindmap)

        # self.checkUrlAccess( self.mindmapUrl )

        if True:
            self.info( "isHTML= '%s'" %(self.isHTML) )
            self.info( "mindmap= '%s'" %(mindmap) )
            self.info( "width= '%s'" %(self.width) )
            self.info( "height= '%s'" %(self.height) )
            self.info( "mindmap-url= '%s'" %(self.mindmapUrl) )
            self.info( "isFatal= '%s'" %(self.isFatal) )
            self.usage()


    """
        Compute the result of the macro call.
    """
    def computeResult(self):
        result = "".join( self.messages )
        if not self.isFatal:
            self.computeApplet()
            result += "".join( self.applet )

        if self.isHTML:
            self.result = self.macro.formatter.rawHTML( result )
        else:
            self.result = result


    """
        Compute the applet link or applet tag (depending on formatter)
    """
    def computeApplet( self ):
        if self.isHTML:
            applet = """
<!--
 - code generated by FreeMindBrowser macro -
 - see http://freemind.sourceforge.net -
-->
<APPLET CODE="%s"
        ARCHIVE="%s"
        WIDTH="%s" HEIGHT="%s" >
  <PARAM NAME="type" VALUE="application/x.java-applet;version=1.4">
  <PARAM NAME="scriptable" VALUE="false">
  <PARAM NAME="modes" VALUE="freemind.modes.browsemode.BrowseMode">
  <PARAM NAME="browsemode_initial_map" VALUE="%s">
  <PARAM NAME="initial_mode" VALUE="Browse">
  <PARAM NAME="selection_method" VALUE="selection_method_direct">
  <PARAM NAME="X" VALUE="XX">
</APPLET>

            """ %( FMBMacro.appletClass, self.appletArchive, self.width, self.height, self.mindmapUrl )
            self.applet.append( applet )

        else:
            self.applet.append( self.macro.formatter.url( 1, self.mindmapUrl ) )
            self.applet.append( self.macro.formatter.url( 0 ) )


    # # # # # # # # # # # #
    # message methods
    # # # # # # # # # # # #
    def info( self, msg ):
        if debug:
            self.msg( 'Info: ' + msg )

    def warning( self, msg ):
        self.msg( 'Warning: ' + msg )

    def error( self, msg ):
        self.msg( 'Error: ' + msg )

    def fatal( self, msg ):
        self.msg( 'Fatal: ' + msg )
        self.isFatal = True

    def msg( self, msg ):
        msg = "FreeMindBrowser-Macro:" + msg
        print msg
        if self.isHTML:
            msg = '<h1 style="font-weight:bold;color:blue">' + msg.replace( '\n', '\n<br/>') + '</h1>'

        self.messages.append(msg)


    def usage( self ):
        usage = """
        Usage: [[FreeMindBrowser( urlOfMindmap [,width [,height]] )]]
            urlOfMindmap: an URL reaching the mindmap - allowed schemes are 'http:' and 'attachment:'.
            width:        (optional) - width of the applet; default: %s
            height:       (optional) - height of the applet; default: %s
        """ %(self.widthDefault, self.heightDefault)

        self.info( usage )


    """
        Take the given URL of the mindmap, validate it and return an URL that can be linked to from the applet.
    """
    def getMindmapURL( self, url ):

        if url.startswith( 'http:' ):
            return url
        elif url.startswith( 'attachment:'):
            relativeUrl = AttachFile.getAttachUrl( self.macro.formatter.page.page_name, url[11:], self.macro.request )
            qualifiedUrl = self.macro.request.getQualifiedURL( relativeUrl )
            return qualifiedUrl
        else:
            self.warning( "Unrecognized scheme in mindmap URL! Url is '%s'!" %(url) )
            self.usage()
            return url



    """
        Desktop edition returns 200 on non existing resource :-(
        is this correct behaviour?
    """
    def checkUrlAccess( self, url ):
        import urllib

        try:
            obj = urllib.urlopen( url )
            self.info( "urllib.urlopen( %s ) returns:" %(url) )
            self.info( str(obj) )
            self.info( "obj.info(): " )
            self.info( obj.info() )
            obj.close()
        except IOError:
            self.fatal( "Mindmap of specified url [%s] is not accessable." %(self.mindmapUrl) )


# # # # # # # # # # # # # # #
# Macro execution interface
# # # # # # # # # # # # # # #

def execute(macro, args):

    fmb = FMBMacro( macro, args )
    # fmb.execute()
    return fmb.execute()
