# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - exportfile Action macro

    PURPOSE::
        This action macro is used from text_x_exportfile to export to a plain/text file 

    CALLING SEQUENCE::
        called by text_x_exportfile POST Method

    MODIFICATION HISTORY::
        Version 1.6.0-1
        @copyright: 2007 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.
"""
import os
from MoinMoin import wikiutil
from MoinMoin.action import AttachFile
from MoinMoin.util import timefuncs

def execute(pagename, request):
    ticket = request.form.get('ticket', [''])[0]
    if wikiutil.checkTicket(request, ticket):

        attachment_path = AttachFile.getAttachDir(request, pagename)
        timestamp = timefuncs.formathttpdate(int(os.path.getmtime(attachment_path)))
        file = request.form.get('file', [''])[0]
        raw = request.form.get('raw', [''])[0]
        content_type = request.form.get('content-type', [''])[0]

        if content_type == 'text/plain':
            request.emit_http_headers([
                'Content-Type:  %s' % content_type,
                'Last-Modified: %s' % timestamp,
                'Content-Length: %d' % len(raw),
                'Content-Disposition: %s; filename="%s"' % ('attachment', file),
            ])
            request.write(raw)
            return ()
        else:
            return ()
    else:
        return ()

