# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ExportFile parser

    PURPOSE:
      This parser is used to download some content of a wiki page to a file. It needs the action exportfile.py

    CALLING SEQUENCE:
      {{{
      #!ExportFile [file=file]
      = Example =
      }}}

    OPTIONAL KEYWORD PARAMETERS:
        file:              file name to save to

    EXAMPLE:
{{{#!ExportFile
= some wiki mark up =
 * A
 * B
}}}


{{{#!ExportFile file=example.txt
#format plain
AAEE BBAA CCAA
DDDE FFAE BBCD
}}}


{{{#!ExportFile file=example.py
#format python
def format(self, formatter):
    self.pagename = formatter.page.page_name
    self.quoted_pagename = wikiutil.quoteWikinameURL(self.pagename)
    attachment_path = AttachFile.getAttachDir(self.request, self.pagename, create=1)
}}}


    PROCEDURE:
      ABOUT:
      This parser is the result of a discussion with ThiloPfennig about saving conten of a page to a file 
      while editing functionality is done from the wiki. see FeatureRequests/ExportFileAction

    MODIFICATION HISTORY:
        Version 1.6.0-1
        1.6.0-2 some code cleanup
        1.6.0-3 some more code moved to wikiutil
        @copyright: 2007 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.

"""
Dependencies = ['time'] # do not cache
import StringIO, codecs
from MoinMoin.action import AttachFile
from MoinMoin import wikiutil
from MoinMoin.parser import text_moin_wiki

class Parser:
    extensions = '*'
    def __init__(self, raw, request, **kw):
        self.file = 'exportfile.txt'
        test = kw.get('format_args', '')
        if test:
            for arg in kw.get('format_args', '').split(','):
                if arg.find('=') > -1:
                    key, value = arg.split('=')
                    setattr(self, key, wikiutil.escape(value.strip(), quote=1))
        self.raw = raw
        self.request = request
        self.form = request.form
        self._ = request.getText


    def format(self, formatter):
        self.pagename = formatter.page.page_name
        self.quoted_pagename = wikiutil.quoteWikinameURL(self.pagename)
        attachment_path = AttachFile.getAttachDir(self.request, self.pagename, create=1)

        Parser = wikiutil.get_parser(self.request, self.raw)

        lines = self.raw.split('\n')
        raw = []
        for line in lines:
            is_good = True
            for pi in ("#format", "#refresh", "#redirect", "#deprecated",
                       "#pragma", "#form", "#acl", "#language"):
                if line.lower().startswith(pi):
                   is_good = False
                   break
            if is_good:
               raw.append(line)
        raw = '\n'.join(raw)

        out = StringIO.StringIO()
        self.request.redirect(out)
        wikiizer = Parser(raw, self.request)
        wikiizer.format(formatter)
        result = out.getvalue()
        self.request.redirect()
        del out

        self.request.write(result)

        form = """
<form action="%(baseurl)s/%(pagename)s" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="action" value="exportfile">
   <input type="hidden" name="ticket" value="%(ticket)s">
   <input type="hidden" name="file" value="%(file)s">
   <input type="hidden" name="raw" value="%(raw)s">
   <input type="hidden" name="content-type" value="%(content_type)s"> 
   <input type="submit" value="download %(file)s">
</form>""" % {
"baseurl": self.request.getBaseURL(),
"ticket": wikiutil.createTicket(self.request),
"pagename": self.pagename,
"file": self.file,
"content_type": "text/plain",
"raw": raw,
}
        self.request.write(form)
