"""
    MoinMoin - EmbedWikiPage a macro to embed a wiki page from a different wiki
    @license: GNU GPL, see COPYING for details.

    PURPOSE:
        This macro is used to embed a wiki page into the current wikipage.
	It is possible to embed local pages as well as external wiki pages.

	if a WikiName is detected the name is translated into a link to the original page.
	On some circumstances a WikiName is not detected, see RESTRICTIONS.

        The page is embedded temporary and you get at the end a link to edit the original page.

	At this stage it could be used to embed single pages e.g. macro explanaitions from moinmoin

    CALLING SEQUENCE:
       [[EmbedWikiPage(site,name)]]


    INPUTS:
       site: the URL of the wiki where the page is on
       name: the wikiname of the page

    EXAMPLE:
       [[EmbedWikiPage(http://moinmoin.wikiwikiweb.de:8000/,ProcessorMarket/sctable)]]

    PROCEDURE:
      * Editing of an embedded page is always editing the original page.
      * wiki:, wiki:/ or [" "] page and normal !WikiName links are followed to their original locations
      * attachments are embedded

      Please remove the version number from the routine name!

    RESTRICTIONS:
      * at the moment it follows nearly all wiki links

      I have a simple mechanism to detect wiki:, wiki:/ or ["HOWTO"] and normal !WikiName pagelinks

      At the moment I don't find !WikiName which are inserted into tabulars and macros.

      Later on it would be fine to use the icon of the page (favicon)
      to show where are the links from.

    MODIFICATION:
       @copyright: 2004-09-26 by Reimar Bauer (R.Bauer@fz-juelich.de) EmbedWikiPage-1.2.3-1
       2004-09-28: RB 1.2.3-2 !WikiName is now supported (some cases are missing)
       2004-09-28: RB 1.2.3-3 !WikiName rules extended
    DISCUSSION:
       * NEED HELP to find WikiName in some cases



"""
import string
import os
import urllib
from MoinMoin.parser import wiki
from MoinMoin import wikiutil

def fetchfile(urlopener, url):
#Copyright (c) 2002-2003  Gustavo Niemeyer <niemeyer@conectiva.com>
# adopted by Reimar Bauer
    geturl = url+"?action=raw"
    filename, headers = urlopener.retrieve(geturl)
    return filename

def get_urlopener(moinurl):
#Copyright (c) 2002-2003  Gustavo Niemeyer <niemeyer@conectiva.com>
# adopted by Reimar Bauer
    urlopener = urllib.URLopener()
    proxy = os.environ.get("http_proxy")
    if proxy:
        urlopener.proxies.update({"http": proxy})
    return urlopener


def execute(macro, text):

    request=macro.request
    formatter=macro.formatter

    if text:
      args=text.split(',')
    else:
      args=[]
    number_args=len(args)
    if number_args < 2:
      return macro.formatter.sysmsg('Not enough arguments to EmbedWikiPage macro')


    site=wikiutil.escape(string.join(args[0],''), quote=1)
    name=wikiutil.escape(string.join(args[1],''), quote=1)

    url="%(site)s%(name)s" %{
          "site": site,
	  "name": name
	}

    urlopener = get_urlopener(url)

    moinfile = fetchfile(urlopener, url)

    id = open(moinfile, "r")
    txt=id.readlines()
    id.close()

    # simple but not finished

    # I need this routine already to show the macro help pages which are on moinmoin.

    i=0
    for line in txt:

        test=line.lstrip()

	if ((test.find('=')  == -1 ) and (test.find('#!')  == -1 ) and (test.find('{{{')  == -1 )and (test.find('}}}')  == -1 )):


            line=string.replace(line,"attachment:",site+name+'?action=AttachFile&do=get&target=')
            txt[i]=line
	    words=line.split()

	    for w in words:

	        if (w.find('.') > -1):
	            w=string.replace(w,'.','')
                if (w.find(',') > -1):
                   w=string.replace(w,',','')
                if (w.find('!') > 0):
                   w=string.replace(w,'!','')
                if (w.find(';') > -1):
                   w=string.replace(w,';','')
                if (w.find('/') == 0):
                   line=string.replace(line,w,' ['+site+name+w+' '+w+']')

	        if (w.find('wiki:/') > -1):
	           s=string.replace(w,'_','_5f')
	           line=string.replace(line,w,s)
	           line=string.replace(line,"wiki:/",site+name+'/')


	        if (w.find('wiki:') > -1):
	           s=string.replace(w,'_','_5f')
	           line=string.replace(line,w,s)
	           line=string.replace(line,"wiki:",site)

                if (string.join(w[0]) == '['):
	           if (string.join(w[1]) == '"'):
	              word=w[2:]
                      pos=word.find('"')
                      word=word[0:pos]
                      pos=w.find(']')
                      w=w[0:pos]
	              line=string.replace(line,w,' ['+site+word+' '+word)



                if wikiutil.isStrictWikiname(w):
                   if (w.find('_') > -1):
	              w=string.replace(w,'_','_5f')
	           line=string.replace(line,w,' ['+site+w+' '+w+']')

        if (test.find('#!EmbedWikiPage') > -1):
	   line=string.replace(line,'#!EmbedWikiPage','#!EmbedWikiPage-1.2.3-3') # it's only if its used to call itselfs, till I know how to test if a site exists
	txt[i]=line
	i=i+1

    wikiizer = wiki.Parser(string.join(txt,""),request)
    wikiizer.format(formatter)

    edit_url=url+'?action=edit'

    edit_icon=request.theme.make_icon("edit")

    request.write('<HR>')
    cmd="<a title=%(edit_url)s href=%(edit_url)s > %(edit_icon)s   %(txt)s</a>" % {
      "edit_url":'"'+edit_url+'"',
      "edit_icon":edit_icon,
      "txt":'Edit embeded page '+name+' on '+site
      }


    request.write(cmd)
    return ""





