# -*- 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
        @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 get_parser(self):
        body = self.raw
        pi_format = self.request.cfg.default_markup or "wiki"
        pi_lines = 0

        # check for XML content
        if body and body[:5] == '<?xml':
            pi_format = "xslt"

        # check processing instructions
        while body and body[0] == '#':
            pi_lines += 1

            # extract first line
            try:
                line, body = body.split('\n', 1)
            except ValueError:
                line = body
                body = ''

            # end parsing on empty (invalid) PI
            if line == "#":
                body = line + '\n' + body
                break

            # skip comments (lines with two hash marks)
            if line[1] == '#': continue

            # parse the PI
            verb, args = (line[1:]+' ').split(' ', 1)
            verb = verb.lower()
            args = args.strip()

            # check the PIs
            if verb == "format":
                # markup format
                pi_format, pi_formatargs = (args+' ').split(' ', 1)
                pi_format = pi_format.lower()
                pi_formatargs = pi_formatargs.strip()

        Parser = wikiutil.searchAndImportPlugin(self.request.cfg, "parser", pi_format)
        return Parser, pi_lines

    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, pi_lines = self.get_parser()
        raw = self.raw.split('\n')
        raw = raw[pi_lines:]
        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)
