from PIL import Image
from templess.templess import template
import py

iconsize = 128
largesize = 400
hugesize = 800

REBUILD = False

def convert(orgpath, newpath, size):
    if not REBUILD and newpath.check():
        return
    new = image.copy()
    new.thumbnail((size, size), Image.ANTIALIAS)
    new.save(newpath.open('w'), 'JPEG')
    return new

here = py.path.local('.');
images = []
for file in here.listdir():
    if file.ext == '.JPG':
        image = Image.open(file.open())
        
        lowername = file.purebasename.lower()

        iconpath = here.join('thumbnail_%s.jpg' % (lowername,))
        convert(file, iconpath, iconsize)
        
        largepath = here.join('large_%s.jpg' % (lowername,))
        convert(file, largepath, largesize)

        hugepath = here.join('huge_%s.jpg' % (lowername,))
        convert(file, hugepath, hugesize)

        images.append({
            'iconpath': iconpath.basename,
            'largepath': largepath.basename,
            'orgpath': file.basename,
            'hugepath': hugepath.basename,
        })

context = {
    'images': images,
}

templatepath = py.path.local('.').join('template.html')
if not templatepath.check():
    templatepath = py.magic.autopath().dirpath().join('template.html')
t = template(templatepath.open())
py.path.local('.').join('index.html').write(
    t.render_to_string(context).encode('UTF-8'))

