'''
Given a directory of jpeg images only, this module takes the input of the required altitude of the 
flight plans by manually checking and a error boundary, all the refined images which fit the boundary 
go to the output directory. The rest go to the discarded directory.

os is used for directory manipulation;
shutil is used for image duplication;
exifread is used for extracting the GPSaltitude info from the image
argparse is used for attributes handling
'''

import os, shutil, argparse
import generateDict

# SPECIFY COMMAND LINE ARGUMENTS
parser = argparse.ArgumentParser(description="jpeg altitude filter")
parser.add_argument('-i', '--input', help='Enter the input jpeg directory', required=True, dest="inDir")
parser.add_argument('-a', '--altitude', help='Enter the GPS altitude of the flight', required=True, dest="alt")
parser.add_argument('-e', '--error', help='Enter the error boundary', required=True, dest="error")
parser.add_argument('-o', '--output', help='Enter the output jpeg directory', required=True, dest="outDir")
parser.add_argument('-d', '--discard', help='Enter the discard jpeg directory', required=True, dest="disDir")
args = parser.parse_args()

# COMMAND LINE ARGUMENT VARIABLES
inputDir = args.inDir
settingAltitude = args.alt
settingErrorBound = args.error
outputDir = args.outDir
restDir = args.disDir

# CREATE OUTPUT DIRS IF NONE EXIST
if os.path.exists(outputDir) == False:
    os.mkdir(outputDir)
if os.path.exists(restDir) == False:
    os.mkdir(restDir)

# Sort images into good and bad folders
def jpegFilter(inputDir, settingAltitude, settingErrorBound, outputDir, restDir): 
    jpegAltitudeDict = generateDict.gen(inputDir)
    for image in jpegAltitudeDict:
        if float(jpegAltitudeDict[image]) >= int(settingAltitude) - int(settingErrorBound) and float(jpegAltitudeDict[image]) <= int(settingAltitude) + int(settingErrorBound):
            shutil.copy(image, outputDir)
        else:
            shutil.copy(image, restDir)

jpegFilter(inputDir, settingAltitude, settingErrorBound, outputDir, restDir) # run with params from command line