from MoinMoin.action import AttachFile
import os

#  I saw another module defining a class so as to manage global variables.
class Globs:
    
    global_string = ''

#  I saw another module defining a class so as to manage default config
#  parameters. I don't have any at the moment, but I might, so I'll just
#  use a placeholder parameter.
class Params:

    something_unused_required_by_last_line = 0 

def execute(macro, args):
    #  This is what I'll return
    html = []

    #  Chop of up received args
    sargs = args.split(',')
    #  Symlink source (i.e. the file that already exists) is first arg.
    source = sargs[0]
    #  Get name of current page, so as to be able to work out path to attachments dir
    current_pagename = macro.formatter.page.page_name
    #  Get attachments dir
    attachment_path = AttachFile.getAttachDir(macro.request, current_pagename, create=1)
    #  Work out the absolute name of the symlink to create
    destination = attachment_path + '/' + os.path.basename(source)

    #  Complain if source is not absolute
    if source[0] != '/':
        message(source + ': is not absolute')
        
    #  Complain if source does not exist
    elif not os.path.exists(source):
        message(source + ': does not exist')

    #  If destination exists, is symlink and points to right thing, accept it as it is.
    elif os.path.lexists(destination) and os.path.islink(destination) and os.readlink(destination) == source:
        pass

    #  If destination exists, is symlink but does not point the right thing, delete and recreate it.
    elif os.path.lexists(destination) and os.path.islink(destination):
        message(source + ': symlink will be redirected')
        os.unlink(destination)
        os.symlink(source, destination)

    #  If destination exists but is not a symlink, complain.
    elif os.path.lexists(destination):
        message(destination + ': already exists but is not symlink')

    #  If destination does not exist then create it.
    else:
        os.symlink(source, destination)

    #  If any any error text was collected append it to what we'll pass back
    if Globs.global_string:
        html.append(u'<table><tr><td colspan="5" style="border-width: 0px;">')
        html.append(u'<font color="#aa0000">%s</font>' % Globs.global_string)
        html.append(u'</td></tr></table>')

    #  return it
    return macro.formatter.rawHTML(u'\n'.join(html))

def message(string):
    Globs.global_string += u'PageComment: %s\n' % string
