#!/usr/bin/python2.7
from __future__ import division
import os, sys
from PIL import Image
from PIL import ImageEnhance
import argparse
CROP_DEFAULT = 'default'
CROP_WHITESPACE = 'whitespace'
parser = argparse.ArgumentParser()
parser.add_argument("--width", type=int)
parser.add_argument("--height", type=int)
parser.add_argument("--crop", choices=[CROP_WHITESPACE, CROP_DEFAULT])
parser.add_argument("--enhance", action="store_true")
parser.add_argument("source", type=str)
parser.add_argument("destination", type=str)
args = parser.parse_args()

infile = args.source
outfile = args.destination
try:
    im = Image.open(infile)
    im = im.convert()
    if args.width is not None or args.height is not None:
        if args.width is None:
            if args.crop and args.crop == CROP_WHITESPACE:
                size = (int(im.size[0]), args.height)
            else:
                size = (int(im.size[0] * args.height / im.size[1]), args.height)
        elif args.height is None:
            if args.crop and args.crop == CROP_WHITESPACE:
                size = (args.width, int(im.size[1]))
            else:
                size = (args.width, int(im.size[1] * args.width / im.size[0]))
        else:
            size = (args.width, args.height)
        if args.crop:
            if args.crop == CROP_DEFAULT:
                width_crop = im.size[0]
                height_crop = int(im.size[0]/(size[0]/size[1]))
                x = 0
                y = int((im.size[1]-height_crop)/2)
                if height_crop > im.size[1]:
                    width_crop = int(im.size[1]/(size[1]/size[0]))
                    height_crop = im.size[1]
                    x = int((im.size[0]-width_crop)/2)
                    y = 0
                im = im.crop((x, y, width_crop+x, height_crop+y))
            im.thumbnail(size, Image.ANTIALIAS)
            if args.crop == CROP_WHITESPACE:
                im_whitespace = Image.new('RGB', (size[0], size[1]), (255, 255, 255))
                im_whitespace.paste(im, ((size[0] - im.size[0]) // 2, (size[1] - im.size[1]) // 2))
                im = im_whitespace
        else:
            im.thumbnail(size, Image.ANTIALIAS)
    if args.enhance:
        enhancer = ImageEnhance.Contrast(im)
        im = enhancer.enhance(1.05)
    im.save(outfile, "JPEG", quality=100)
except IOError as e:
    print("cannot create thumbnail for '%s'" % infile)
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
    sys.exit(os.EX_DATAERR)
