# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - HelpOn Action Macro

    PURPOSE:
        This action macro is used to get help on an other extensions

    SYNTAX:
        http://WikiServer/WikiName?action=HelpOn

    PROCEDURE:
       You get a pull down list of available extensions and after selection 
       the help from inside of the routine is shown
       
       The extensions below the MoinMoin path are indicated by the prefix MM- 
       While the others are indicated by a W- in the list

       Please remove the version number from the filename.

    MODIFICATION HISTORY:
        @copyright: 2005 by MoinMoin:ReimarBauer 
        @license: GNU GPL, see COPYING for details.
        Version: 1.3.5-1
        
        1.3.5-2 bug fix if no routine desription is defined
                minor change from table output to preformatted text
                
        1.3.5-3 code refactored      
        1.3.5-4 PRE does not need an additional line break
        
        1.5.1-5 removed request.cfg.excluded_actions 
        1.5.4-6 2006-07-04 RB: some PEP8 changes
        1.6.0-9 2008-01-10 refactored for 1.6 getting the header is not quite optimal currently
"""

import codecs, os
from MoinMoin import config, wikiutil, user, macro, action, parser
from MoinMoin.Page import Page
from MoinMoin.formatter.text_html import Formatter

def HelpOn_Extract_Help(module_path_name, module_name):
    # if the module is not a file it is defined in __init__
    if not os.path.exists(module_path_name):
        module_path_name = module_path_name.replace(module_name.split(':')[1], '__init__')

    file = codecs.open(module_path_name, 'r')
    lines = file.readlines()
    file.close()

    index = []
    i = 0
    for line in lines:
        if line.strip() == '"""':
            index.append(i)
        i += 1

    if len(index) >= 2:
        txt = lines[(index[0])+1: index[1]]
    else:
        txt = ["no help available for %(name)s" % {"name": module_name}]

    return txt

def HelpOn(request, pagename, module):
    request.formatter = Formatter(request)
    mod = module.split(':')
    module_type = mod[0]
    this_type = module_type.split('-')
    module_type = this_type[1]
    module_name = mod[1]

    if this_type[0] == 'MM':
        module_path_name = "%(path)s/%(module_type)s/%(name)s.py" % {
             "module_type": module_type,
             "path": request.cfg.moinmoin_dir,
             "name": module_name }

    if this_type[0] == 'W':
        module_path_name = "%(path)s/plugin/%(module_type)s/%(name)s.py" % {
             "module_type": module_type,
             "path": request.cfg.data_dir,
             "name": module_name}

    info = HelpOn_Extract_Help(module_path_name, module)
    html = "<PRE>%(txt)s</PRE>" % {
               "txt": '\n'.join(info)}

    request.emit_http_headers()
    request.setContentLanguage(request.lang)
    request.theme.send_title('Helpon %s' % module_name, pagename=pagename)
    request.write(request.formatter.startContent("content"))
    request.write(html)
    request.write(request.formatter.endContent())
    request.theme.send_footer(pagename)
    return


def execute(pagename, request):
    thispage = Page(request, pagename)
    if not request.user.valid:
        msg="Please log in"
        request.theme.add_msg(msg)
        thispage.send_page()
        return

    _ = request.getText
    actname = __name__.split('.')[-1]

    if request.form.has_key('button') and request.form.has_key('ticket'):
        if not wikiutil.checkTicket(request, request.form['ticket'][0]):
            msg = _('Please use the interactive user interface for HelpOn extensions!')
            request.theme.add_msg(msg)
            thispage.send_page()
            return
        module = request.form.get('helpon', [u''])[0]
        return (HelpOn(request, pagename, module))

    html = []

    for name in action.getNames(request.cfg):
        html.append("<OPTION>MM-action:%(name)s</OPTION>" % {"name": name})

    for name in wikiutil.wikiPlugins('action', request.cfg):
        html.append("<OPTION>W-action:%(name)s</OPTION>" % {"name": name})

    for name in macro.getNames(request.cfg):
        html.append("<OPTION>MM-macro:%(name)s</OPTION>" % {"name": name})

    for name in wikiutil.wikiPlugins('macro', request.cfg):
        html.append("<OPTION>W-macro:%(name)s</OPTION>" % {"name": name})

    for name in  parser.modules:
        html.append("<OPTION>MM-parser:%(name)s</OPTION>" % {"name": name})

    for name in wikiutil.wikiPlugins('parser', request.cfg):
        html.append("<OPTION>W-parser:%(name)s</OPTION>" % {"name": name})

    formhtml = '''
<form method="post" action="">
<select name="helpon" size="1">
%(option)s
</select>
<input type="hidden" name="action" value="%(actname)s">
<input type="submit" name="button" value="%(button)s">
<input type="hidden" name="ticket" value="%(ticket)s">
<p>
</form>''' % {
    'actname': 'HelpOn',
    'ticket': wikiutil.createTicket(request),
    'option': '\n'.join(html),
    'button': 'Help'}

    request.theme.add_msg(formhtml)
    thispage.send_page()
    return

