'''
given pile of pictures, open image, go to exif, get creation date, close file, move at OS level to subdir of form mm-dd

-s: print commands it thinks it should do to standard out

Credit: recursive directory search thanks to https://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python

will need to make a script that can choose from these:
guide:
canon6D         - Nic Arnold's DSLR, 20.2MP
nikonD3300      - Erin Lewis's DSLR, 24.2MP
GoPro           - body mounted video camera
Nic-phone       - iPhone 5s
Erin-phone      - iPhone
Kristin-phone   - iPhone
Deeksha-phone   - HTC
Charlie-phone   - Samsung
Gale-phone      - iPhone
Tara-phone      - iPhone(?)
DJI-phantom3a   - sony sensor DJI camera, 12MP

should also eliminate whitespace in file names but that's the last thing to do
'''
from os import listdir, walk, rename, makedirs
from os.path import isfile, join, split, exists
import sys
import exifread
import argparse

# assume dates take the format YYYY:MM:DD HH:MM:SS
def datefolder(datestring):
	# clean up the datestring
	datestring = datestring.split(" ",2)
	datestring = datestring[0].replace("2016:","")
	datestring = datestring.replace(":","-")
	if debug:
		print datestring
	return datestring

def get_filepaths(directory):
    """
    This function will generate the file names in a directory 
    tree by walking the tree either top-down or bottom-up. For each 
    directory in the tree rooted at directory top (including top itself), 
    it yields a 3-tuple (dirpath, dirnames, filenames).
    """
    file_paths = []  # List which will store all of the full filepaths.

    # Walk the tree.
    for root, directories, files in walk(directory):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = join(root, filename)
            file_paths.append(filepath)  # Add it to the list.

    return file_paths  # Self-explanatory.

# by default, it's a production run
debug = 0
sandbox = 0

parser = argparse.ArgumentParser(description='Image Date Sort')
parser.add_argument("-s", action="store", dest="s", help="sandbox mode", type=int)
parser.add_argument("-d", action="store", dest="d", help="debug mode", type=int)
args = parser.parse_args()

debug = args.d
sandbox = args.s

logfilename = "log.dat"
mypath = "/media/r10_vol/Iceland"
destroot = "/media/r10_vol/Iceland/clean"

# logfilename = "log.dat"
# mypath = "testdir/0708old"
# destroot = "testdir/0708new"

# done setting up #

full_file_paths = get_filepaths(mypath)

for file in full_file_paths:
	
	f = open(file, 'rb')
	head, tail = split(file)			

	tags = exifread.process_file(f)

	for tag in tags.keys():
		if "Image DateTime" in tag:
			mydate = str(tags[tag])
			mydate = datefolder(mydate)
			
			if (debug):
				print mydate
			
			#assumes only one additional layer in the directory hierarchy
			destpath = destroot + "/" + mydate
			
			if not exists(destpath):
			    makedirs(destpath)
			
			# build a path with the same basename as the existing file
			destpath = destpath + "/" + tail

			# be sure not to overwrite an existing filename
			count = 0
			while exists(destpath):
				count += 1
                destpath = destpath + '_' + str(count)

			# log what you're doing
			logfile = open(logfilename,'a')
			logfile.write(file + "\t-->\t" + destpath + "\n")

			# just stop if you're testing/playing
			if (sandbox):
				logfile.close()
			
			# close the log and move the file if you're in production	
			else:
				logfile.close()
  				rename(file, destpath)
  				
	f.close()

# get date
# move file to folder with that date in /media/r10_vol/Iceland/clean