#!/usr/bin/env python
# encoding=utf-8

import locale
import mimetypes
import os
import re


SKIP_RE = ".*\.(xml|html|md|thumbnail\.jpg)$"


def srt(what):
    return sorted(what, key=lambda x: x.lower())


def only_pictures(dirs, files):
    if dirs:
        return False

    for fn in files:
        if not fn.lower().endswith(".jpg"):
            return False

    return True


def render_album(_dirname, _files):
    html = u"<div id='album'>"
    for fn in _files:
        tn = fn[:-3] + "thumbnail.jpg"
        html += u"<a href='%s' title='%s'><img src='%s' alt='thumbnail'/></a>" % (fn, fn, tn)
    return html


def render_title(path):
    html = u"<h1>Folder "
    parts = path.split(os.path.sep)

    _parts = []
    for part in path.split(os.path.sep):
        _skip = len(parts) - len(_parts)
        _parts.append(part)
        _path = u"/".join(_parts)
        _name = os.path.basename(_path) or u"root"
        if _name == ".":
            _name = "root"
        if _skip > 1:
            _link = u"../" * (_skip - 1)
            html += u"<a href='%s_index.html'>%s</a>/" % (_link, _name)
        else:
            html += _name + u"/"

    return html + u"</h1>"


def is_image(filename):
    return os.path.splitext(filename.lower())[1] in (".jpg", ".png")


def get_file_size(fn):
    return locale.format("%d", os.stat(fn).st_size, grouping=True)


def update_folder(path):
    skip_re = re.compile(SKIP_RE)

    for _dirname, _dirs, _files in os.walk(path):
        html = u"<html><head>"
        html += u"<style type='text/css'>table { border-collapse: collapse } td { border: solid 1px #ddd; padding: 2px 4px } img { vertical-align: middle } td:nth-child(3) { text-align: right } a { color: #008 } #album img { margin: 0 2px 2px 0; padding: 1px; border: solid 1px #ddd }</style>"
        html += u"<meta http-equiv='content-type' content='text/html; charset=utf-8'/>"
        html += u"<link rel='alternate' type='application/rss+xml' href='http://files.umonkey.net/%s/rss.xml'/>" % _dirname[2:]
        html += u"<title>Folder %s</title>" % _dirname[1:]
        html += u"<script type='text/javascript'>var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18002512-4']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ?  'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();</script>"
        html += u"</head><body>"
        html += render_title(_dirname)

        _files = [fn for fn in srt(_files) if not skip_re.match(fn.lower())]

        if only_pictures(_dirs, _files):
            html += render_album(_dirname, _files)
        else:
            html += u'<table><tbody>'
            for fn in srt(_dirs):
                html += u"<tr><td colspan='3'><a href='%s/_index.html'>%s/</a></td></tr>" % (fn, fn)
            for fn in _files:
                if os.path.splitext(fn)[1] in (".xml", ".html") or fn.endswith(".thumbnail.jpg"):
                    continue
                _fn = os.path.join(_dirname, fn)
                _link = u"<a href='%s'>%s</a>" % (fn, fn)

                _tn = _fn[:-3] + "thumbnail.jpg"
                if is_image(fn) and os.path.exists(_tn):
                    _link = u"<a href='%s' title='%s'><img src='%s' alt='thumbnail'/></a> " % (fn, fn, os.path.basename(_tn)) + _link

                html += u"<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (_link, mimetypes.guess_type(_fn)[0] or "binary/octet-stream", get_file_size(_fn))

        html += u'</body></html>'

        f = open(os.path.join(_dirname, '_index.html'), 'wb')
        f.write(html)
        f.close()

if __name__ == '__main__':
    locale.setlocale(locale.LC_ALL, "en_US.UTF-8")  # for proper number formatting
    update_folder('.')
