#!/usr/bin/env python
from __future__ import division
import os, sys
from PIL import Image
from PIL import ImageEnhance
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--width", dest="width", type=int, required=True)
parser.add_argument("--height", dest="height", type=int, required=True)
parser.add_argument("--crop", action="store_true", required=False)
parser.add_argument("--keep-aspect-ratio", dest="keep_aspect_ratio", action="store_true", required=False)
parser.add_argument("source", type=str)
parser.add_argument("destination", type=str)
args = parser.parse_args()

size = args.width, args.height
infile = args.source
outfile = args.destination
try:
    im = Image.open(infile)
    im = im.convert()
    if args.crop:
        width_crop = im.size[0]
        height_crop = int(im.size[0]/(args.width/args.height))
        width_padding = 0
        height_padding = int((im.size[1]-height_crop)/2)
        if height_crop > im.size[1]:
            width_crop = int(im.size[1]/(args.height/args.width))
            height_crop = im.size[1]
            width_padding = int((im.size[0]-width_crop)/2)
            height_padding = 0
        print((width_padding, height_padding, width_crop+width_padding, height_crop+height_padding))
        im_crop = im.crop((width_padding, height_padding, width_crop+width_padding, height_crop+height_padding))
        im_result = im_crop.resize(size, Image.ANTIALIAS)
    else:
        im.thumbnail(size, Image.ANTIALIAS)
        if args.keep_aspect_ratio:
            im_result = im
        else:
            im_result = Image.new('RGB', (args.width, args.height), (255, 255, 255))
            im_result.paste(im, ((args.width - im.size[0]) / 2, (args.height - im.size[1]) / 2))
    enhancer = ImageEnhance.Contrast(im_result)
    im_result = enhancer.enhance(1.05)
    im_result.save(outfile, "JPEG", quality=100)
except IOError:
    print("cannot create thumbnail for '%s'" % infile)
