# -*- coding: utf-8 -*-
"""
    MoinMoin - Thumbnails - make thumbnail versions of attached images

    @copyright: (c) Elias Pschernig
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin.Page import Page
from MoinMoin.action import AttachFile
import os, re
from MoinMoin import config

try:
    from PIL import Image
except ImportError:
    class Image:
        ANTIALIAS = 0
        def open(path):
            self = Image()
            self.path = path
            output = os.popen("identify '%s'" % self.path).read()
            mob = re.compile(r" (\d+)x(\d+) ").search(output)
            if mob:
                w = int(mob.group(1))
                h = int(mob.group(2))
                self.size = w, h
            else:
                self.size = 0, 0
            return self
        open = staticmethod(open) # For Python 2.3 compatibility
        def convert(self, *args, **kw):
            return self
        def copy(self):
            c = Image()
            c.path = self.path
            c.size = self.size
            return c
        def thumbnail(self, size, flags):
            os.popen("convert -resize %dx%d '%s' '%s'" % (size[0],
                size[1], self.path, self.path + "TEMP"))
        def save(self, filename):
            os.popen("convert '%s' '%s'" % (self.path + "TEMP", filename))
            os.popen("rm '%s'" % (self.path + "TEMP"))

# Specify here the default extensions and sizes. They are overridden by the wiki
# config.
default_thumbextensions = ["png", "jpg", "gif"]
default_thumbsizes = [160, 320, 640]
default_thumbname = "tmp.%(size)s.%(base)s.jpg"
default_thumbignore = ["^tmp\\..*"]

def execute(pagename, request):
    if not request.user.may.write(pagename):
        Page(request, pagename).send_page(request,
            "You need write permissions on this page to update thumbnails.")

    extensions = getattr(request.cfg, "thumbextensions", default_thumbextensions)
    thumbsizes = getattr(request.cfg, "thumbsizes", default_thumbsizes)
    thumbname = getattr(request.cfg, "thumbname", default_thumbname)
    ignore = getattr(request.cfg, "thumbignore", default_thumbignore)

    dir = AttachFile.getAttachDir(request, pagename)
    thumbs = ""
    try:
        pics = [x for x in os.listdir(dir) if [x.endswith(y) for y in extensions]]
        for pic in pics:
            # Do not make thumbnails for thumbnails.
            for pattern in ignore:
                if re.compile(pattern).match(pic):
                    break
            else:
                base, ext = os.path.splitext(pic)
                im = Image.open(os.path.join(dir, pic))
                for size in thumbsizes:
                    # Never make the thumbnail bigger than the original.
                    if im.size[0] <= size and im.size[1] <= size: continue
                    thumb = im.copy()
                    thumb = thumb.convert("RGB")
                    thumb.thumbnail((size, size), Image.ANTIALIAS)
                    name = thumbname % {"base" : base, "size" : size}
                    thumb.save(os.path.join(dir, name))
                    thumbs += """<a href="%s">%s</a><br />""" % (
                        AttachFile.getAttachUrl(pagename, name,
                        request).replace("do=get", "do=view"), name)
    except OSError:
        thumbs += "None<br />"
    Page(request, pagename).send_page(request,
"""
These thumbnails have been updated:<br />
%s
Use the attachements view to delete thumbnails.
""".strip() % thumbs)


