#!/usr/bin/env python

import sys
import os
import Image

from cropy.entropy import entropy_crop
from skimage import io
from optparse import OptionParser


if __name__ == '__main__':

    usage = "usage: %prog -i [input image] -r [width] [height] -o [output name] -s [maxSteps]"\
    "where [width] and [height] are the requested crop size"
    parser = OptionParser(usage=usage)
    parser.add_option("-i", "--image", dest="input_image", help="Input Image File")
    parser.add_option("-r", "--resolution", dest="resolution", help="Output Image size [width], [height]", nargs=2)
    parser.add_option("-o", "--output", dest="output", help="Output Image File Name")
    parser.add_option("-s", "--maxSteps", dest="maxSteps", help="Maximum slicing steps")
    parser.add_option("-v", "--verbose", dest="verbose", help="Trigger Verbose Printing", action="store_true")
    (options, args) = parser.parse_args()

    if not options.input_image or not options.resolution:
        print "Incorrect Usage; please use -usage"
        sys.exit(2)
    if options.verbose:
        global verbose
        verbose = True

    if not options.maxSteps:
        maxSteps = float(10)
    else:
        maxSteps = float(options.maxSteps)

    try:
        input_image = options.input_image
        crop_width, crop_height = int(options.resolution[0]), int(options.resolution[1])
    except:
        print "Incorrect Usage; please use --help"
        sys.exit(2)

    if not options.output:
        output = os.path.splitext(
            options.input_image)[0] + "." + str(crop_width) + "." + str(crop_height) + ".jpg"
    else:
        output = options.output

    im = io.imread(input_image, as_grey=True)  # Load an image with float format

    x_offset, y_offset = entropy_crop(im, crop_width, crop_height, maxSteps)
    imfin = Image.open(input_image)
    region = imfin.crop((x_offset, y_offset, crop_width + x_offset, crop_height + y_offset))
    region.save(output)
