#!/usr/bin/python

import os
import os.path
import shutil
import re
import random

mogrify = "/usr/bin/mogrify"
composite = "/usr/bin/composite"
montage = "/usr/bin/montage"
quality = "70"
offset = 5
thumbwidth = 320
thumbheight = 200
background = "white"
tilewidth = 10 
tileheight = 10
seed = "oojimaflip"

bigfiles = [(1,4), (3,3), (4,6), (6,2), (7,7)]

imgmatcher = re.compile("^.*\\.[Jj][Pp][Ee]?[Gg]$")

def thumb(file, newfile, width, height):
	if (height is not None):
		height = str(height)
	else:
		height = ""

	shutil.copyfile(file, newfile)
	os.spawnl(os.P_WAIT, mogrify, mogrify,
	"-size", str(width)+ "x" + str(height),
	"-resize", str(width) + "x" + str(height),
	"-quality", quality,
	newfile)

def crop(file, width, height):
	os.spawnl(os.P_WAIT, mogrify, mogrify,
	"-crop", str(width) + "x" + str(height),
	"-gravity","center",
	"-quality", quality,
	file)

def compose(file1, file2, newfile, width, height):
	os.spawnl(os.P_WAIT, compose, compose,
	"-geometry", "+",str(width + offset),
	"-background", background,
	"-quality", quality,
	"-tile",str(tilewidth) + "x" + str(tileheight),
	file1,
	file2,
	newfile) 

files = os.listdir(".")

for file in files:
	if (imgmatcher.match(file) is not None):
		print file
		if (not os.path.exists(file + "-thm") or os.stat(file).st_mtime > os.stat(file + "-thm").st_mtime):
			thumb(file, file + "-thm", thumbwidth, None)
			crop(file + "-thm", thumbwidth, thumbheight)
		if (not os.path.exists(file + "-thm2") or os.stat(file).st_mtime > os.stat(file + "-thm2").st_mtime):
			thumb(file, file + "-thm2", thumbwidth * 2 + offset * 2, None)
			crop(file + "-thm2", thumbwidth * 2 + offset * 2, thumbheight * 2 + offset * 2)

reducedfiles = []
for file in files:
	if (imgmatcher.match(file) is not None):
		reducedfiles.append(file)

files = reducedfiles

random.seed(seed)
random.shuffle(files)

for bigfile in bigfiles:
	files.insert(bigfile[1] + 1 + tilewidth * bigfile[0], None)
	files.insert(bigfile[1] + tilewidth * (bigfile[0] + 1), None)
	files.insert(bigfile[1] + 1 + tilewidth * (bigfile[0] + 1), None)

fileargs = [ 
	montage,
	"-adjoin",
	"-geometry",str(thumbwidth) + "x" + str(thumbheight) + "+" + str(offset) + "+" + str(offset),
	"-tile",str(tilewidth) + "x" + str(tileheight) ]

for file in files:
	if file is None:
		fileargs.append("null:")
	elif (imgmatcher.match(file) is not None):
		fileargs.append(file + "-thm")

fileargs.append("test.jpg")

os.spawnv(os.P_WAIT, montage, fileargs)

for bigfile in bigfiles:
	print files[bigfile[1] + tilewidth * bigfile[0]] + "-thm2"
	os.spawnl(os.P_WAIT, composite, composite,
	"-geometry", "+" + str(bigfile[1] * (thumbwidth + offset * 2) + offset) + "+" + str(bigfile[0] * (thumbheight + offset * 2) + offset),
	files[bigfile[1] + tilewidth * bigfile[0]] + "-thm2",
	"test.jpg",
	"test.jpg")

