# -*- coding: utf-8 -*-
"""
    MoinMoin - ThumbGallery Macro
    Version 0.1

    Show all the attached images in a table of thumbnails with links to the full-size images

    Usage:
    <<ThumbGallery()>>
    <<ThumbGallery(columns, imgwidth)>>
        columns: number of columns in a table (default 3)
        imgwidth: width of every thumbnail in pixels (default 300)

    Requires the Thumbnail macro/action by Kenneth Bull

    @copyright: 2010 by Alexander 'Loki' Agibalov
    Reused some pieces of code from the ImageBrowser Macro by Kenneth Bull

    @license: GNU GPL, see COPYING for details.

"""


def getImageList(request, pagename):
    from MoinMoin.action.AttachFile import _get_files, getFilename, getAttachUrl
    from MoinMoin import wikiutil
    import os, mimetypes
    files = _get_files(request, pagename)
    fmt = request.formatter
    imgs = []
    for f in files:
        if os.path.isfile(getFilename(request, pagename, f)) and (str(mimetypes.guess_type(f)[0])[:5] == "image"):
            imgs.append(wikiutil.escape(f))
    return imgs


def buildCell(request, page, cell, imgwidth):
    from MoinMoin.action.AttachFile import getAttachUrl
    from MoinMoin import config
    fmt = request.formatter
    ret = fmt.url(1, getAttachUrl(page.page_name, cell, request)) + \
          u'<img src="%s?action=Thumbnail&amp;target=%s&amp;w=%d">' % (page.url(request), cell, imgwidth) + \
          fmt.url(0)
    return ret


def macro_ThumbGallery(macro, columns=3, imgwidth=300):
    from MoinMoin.action import AttachFile
    import math
    page = macro.formatter.page
    imglist = getImageList(macro.request, page.page_name)
    ret = u'<table>'
    # number of rows in html table for the given number of columns
    rowcnt = int(math.ceil(len(imglist) / (columns + 0.0)))
    for r in range(rowcnt):
        ret = ret + u'<tr>'
        for c in range(columns):
            pos = c + r * columns
            if pos > (len(imglist) - 1):
                cell = u'&nbsp;'
            else:
                cell = imglist[pos]
            ret = ret + u'<td>' + buildCell(macro.request, page, cell, imgwidth) + u'</td>'
        ret = ret + u'</tr>'
    ret = ret + u'</table>'
    return ret

