#!/usr/bin/env python

# Import modules
import sys
import cv2
import numpy as np
from os import path
from PIL import Image


# Generic failure
generic_failure = 99


# Check the file path
def checkFilePath(filename):
    # Initialize to failure
    ret = 2

    if path.exists(filename):
        ret = 0

    return ret


# Load and decode an image
def loadAndDecode(filename):
    # Check the image
    img_check = Image.open(filename)
    img_check.load()

    # Read the image
    im = cv2.imread(filename)

    return im


# Store the image to the hard drive
def storeImage(im, outdir, filename):
    cv2.imwrite(outdir + "/" + filename, im)


# Flip the image through the horizontal axis
def flipImage(im):
    hor_axis = 0

    return cv2.flip(im, hor_axis)


# Concatenate two images horizontally
def concImages(im1, im2):
    conc_axis = 1

    return np.concatenate((im1, im2), conc_axis)


# Image flip script
def dt_image_flip(filename, outdir):

    ret = generic_failure

    # Check the file path
    ret = checkFilePath(filename)

    if ret == 0:
        # Load and decode the image
        im = loadAndDecode(filename)

        if im is None:
            ret = 3
        else:
            # Store the regular image to the hard drive
            storeImage(im, outdir, "regular.jpg")

            # Flip the image through the horizontal axis and store it
            im_flipped = flipImage(im)
            storeImage(im_flipped, outdir, "flip.jpg")

            # Concatenate two images horizontally and store the res. image
            im_conc = concImages(im, im_flipped)
            storeImage(im_conc, outdir, "side-by-side.jpg")

    return ret


# dt-image-flip script
try:
    ret = dt_image_flip(sys.argv[1], sys.argv[2])
except IOError:
    ret = 3
except:
    ret = generic_failure

sys.exit(ret)
