# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - Thumbnail Action
    Version 0.2

    ?action=Thumbnail&w=<width>&h=<height>&target=<attachment>
    ?action=Thumbnail&h=<height>&target=<attachment>
    ?action=Thumbnail&w=<width>&target=<attachment>
    ?action=Thumbnail&target=<attachment>

    Displays a thumbnail of an image attachment.
    If height or width are missing, the missing dimension is calculated using the image's aspect ratio.
    If both height and width are missing, they default to 64x64.

    @copyright: 2007 by Kenneth Bull
    @license: GNU GPL, see COPYING for details.

"""

import os, mimetypes, shutil
from subprocess import Popen, PIPE, call
from MoinMoin import util, wikiutil
from MoinMoin.Page import Page
from MoinMoin.util import filesys, timefuncs#, MoinMoinNoFooter
from MoinMoin.action.AttachFile import _access_file, getAttachDir, error_msg

convert = 'C:/Progra~1/ImageMagick-6.3.4-Q16/convert'
cached = True

def getThumbnailUrl(pagename, filename, request, width=None, height=None):
    return "%s/%s?action=%s%s%s&target=%s" % (
        request.getScriptname(),
        wikiutil.quoteWikinameURL(pagename),
        action_name,
        width and ("&w=%d" % width) or "",
        height and ("&h=%d" % height) or "",
        filename,
        )

def getFilename(pagename, filename, width=None, height=None, request):
    if (width is None) and (height is None):
        width = 64
        height = 64
    thumbnail = "thumbnail_%(fpath)s_%(size)s.png" % {'fpath': wikiutil.quoteWikinameFS(filename), 'size': size}
    thumbpath = Page(request, pagename).getPagePath("thumbnails", check_create=False)
    thumbpath = os.path.join(thumbpath, thumbnail)
    return thumbpath

def execute(pagename, request):
    _ = request.getText
    
    if not request.user.may.read(pagename):
        error_msg(pagename, request, _('You are not allowed to view thumbnails of attachments from this page.'))
        return
        
    filename, fpath = _access_file(pagename, request)
    if not filename: return # error msg already sent in _access_file

    timestamp = timefuncs.formathttpdate(int(os.path.getmtime(fpath)))
    if request.if_modified_since == timestamp:
        request.http_headers(["Status: 304 Not modified"])
        request.setResponseCode(304)

    else:
    	fpath = fpath.replace("\"", "\\\"");
    	(w, h) = (0, 0)
        if request.form.get('w', [''])[0] and request.form.get('w', [''])[0].strip().isdigit():
            w = int(request.form.get('w', [''])[0].strip())
        if request.form.get('h', [''])[0] and request.form.get('h', [''])[0].strip().isdigit():
            h = int(request.form.get('h', [''])[0].strip())
        size = w and (h and ("%(w)dx%(h)d" % {'w': w, 'h': h}) or ("%d" % w)) or h and ("x%d" % h) or "64x64"

        thumbnail = "thumbnail_%(fpath)s_%(size)s.png" % {'fpath': wikiutil.quoteWikinameFS(filename), 'size': size}

        if cached:
            thumbpath = Page(request, pagename).getPagePath("thumbnails", check_create=True)
            thumbpath = os.path.join(thumbpath, thumbnail)

            if not os.path.isfile(thumbpath) or int(os.path.getmtime(fpath)) > int(os.path.getmtime(thumbpath)):
                cmd = "%(convert)s \"%(fpath)s\" -thumbnail %(size)s -background transparent -gravity center -extent %(size)s png:\"%(thumbpath)s\"" % \
                      {'convert': convert, 'fpath': fpath, 'size': size, 'thumbpath': thumbpath}
                pipe = Popen(cmd, shell=True, bufsize=8192, stderr=PIPE)
                pipe.wait()
                if not os.path.isfile(thumbpath):
                    error_msg(pagename, request, _("Unable to generate thumbnail.\n%(error)s\n%(cmd)s\n") % {'error': pipe.stderr.read(), 'cmd': cmd})
                    pipe.stderr.close();
                    return
                pipe.stderr.close();
            
            request.http_headers([
                'Content-Type: image/png',
                'Last-Modified: %s' % timestamp,
                'Content-Length: %d' % os.path.getsize(thumbpath),
                'Content-Disposition: inline; filename="%s"' % thumbnail,
            ])

            # send data
            shutil.copyfileobj(open(thumbpath, 'rb'), request, 8192)

        else:    	
            pipe = Popen("%(convert)s \"%(fpath)s\" -thumbnail %(size)s -background transparent -gravity center -extent %(size)s png:-" % {'convert': convert, 'fpath': fpath, 'size': size},
                         shell=True, bufsize=8192, stdout=PIPE)
            buf = ''
            while pipe.poll() == None:
                buf += pipe.stdout.read()
            pipe.stdout.close()
            
            if (pipe.poll() != 0):
                error_msg(pagename, request, _("Unable to generate thumbnail."))
                return
                
            request.http_headers([
                'Content-Type: image/png',
                'Last-Modified: %s' % timestamp,
                'Content-Length: %d' % len(buf),
                'Content-Disposition: inline; filename="%s"' % thumbnail
            ])

            # send data
            request.write(buf)

    #raise MoinMoinNoFooter
