#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
#  Jean-Pierre POURREZ
#

from math import sqrt, ceil
from PIL import Image
from os import listdir, mkdir, remove
from shutil import rmtree
from os.path import join, splitext

from urllib.request import urlretrieve
from zipfile import ZipFile
from tempfile import mkdtemp
import sys

URL = 'https://downloads.gosquared.com/pixels/flags.zip'
IMG_PATH = 'flags-iso/flat'
SIZE = 32
CLASS_NAME = 'kz-flag'
TARGET = 'flags'

def isImage(filename):
	try:
		im = Image.open(filename)
		return True
	except:
		return False

def process(path):
	html = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<title>Flags</title>
	<style>
		body { background-color: #444; }
		body > div { display: flex; flex-wrap: wrap; }
		body > div div {
		    margin: 5px;
		    background: #e8e8e8;
		    text-align: center;
		    padding: 0 2px;
		}
	</style>
	<link rel="stylesheet" href="%s.css" />
</head>
<body>
<div>
''' % TARGET
	css = '''
.%s {
	/* Auto-build by flags.py */
	display: block;
	width: %dpx;
	height: %dpx;
	background-image: url('%s.png');
	background-color: #eee;
}
''' % (CLASS_NAME, SIZE, SIZE, TARGET)

	files = [f for f in listdir(path) if isImage(join(path, f))]
	xMax = int(sqrt(len(files)) + 1)
	yMax = ceil(len(files) / xMax)
	sprite = Image.new("RGBA", (SIZE * xMax , SIZE * yMax))
	for i, f in enumerate(files):
		im = Image.open(join(path, f))
		col = SIZE * (i % xMax)
		row = SIZE * int(i / xMax)
		(fn, ext) = splitext(f)
		sprite.paste(im, (col, row))
		css += ".%s.%s { background-position: %4dpx %4dpx; }\n" % (CLASS_NAME, fn, -col, -row)
		html +=  '<div><span class="%s %s">&nbsp;</span><span>%s</span></div>\n' %(CLASS_NAME, fn, fn)
	html += '''</div>
</body>
</html>
'''
	# Save all flags in one image
	sprite.save('%s.png' % TARGET, 'png')
	print('%s.png built' % TARGET)

	# Save the test HTML page
	with open('%s.html' % TARGET, 'w') as f:
		f.write(html)
		print('%s.html built' % TARGET)

	# Save the CSS style sheet
	with open('%s.css' % TARGET, 'w') as f:
		f.write(css)
		print('%s.css built' % TARGET)

def progressbar(block, count, total):
	bar_len = 60
	filled_len = int(round(bar_len * count / total))
	percents = round(100.0 * count / total, 1)
	bar = '=' * filled_len + '-' * (bar_len - filled_len)
	# print('[%s] %3d%s' % (bar, percents, '%'), end='\r')
	sys.stdout.write('[%s] %3d\r' % (bar, percents))
	sys.stdout.flush()

def main(args):

	print('Downloading ' + URL + ' ...')
	filename, headers = urlretrieve(URL, reporthook=progressbar)
	print('')
	if headers.get_content_type() == 'application/zip':
		print('Unzip ' + filename)
		tempdir = mkdtemp()
		with ZipFile(filename) as f:
			f.extractall(tempdir)
		process(join(tempdir, IMG_PATH, '%d' % SIZE))
		rmtree(tempdir)
		remove(filename)
		print('Done !')
	else:
		print('Bad Content-Type: %s' % 'application/zip')
	return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))