#!/cygdrive/c/python34/python
#
# Program that saves the original bird picture files after Photoshop processing.
# Photoshop moves the thumbnail and displayed resolution images to the appropriate
# directory.
# This program moves the original image(s) files, .JPG/.CR2 from specified directory
# to the htdocs Full_image page for the date specified in the .jpg or .CR2 file.
# Misc. files of the same name are also moved: .xmp, .PSD
#
import pdb
import exifread
import subprocess
import os.path
import os
import shutil
from string import digits
from bird_utils import ls_cmd
from bird_utils import get_subdirs
from bird_utils import get_metdata_date
alist=[]        # Store one or more possible answer to which directory
images={}       # dictionary storing images from name without extension
afiles=[]       # stores filenames to move

htdir_base = "e:/htdocs/birds/"
htdir_end = "Images/Full_res/"
pdir_base = "c:/users/Nancy/Pictures/"
mv_files = "e:/htdocs/birds/progs/data/moveit.txt"

    # get all the subdirectories starting at 'pdir_base'/2*
    # e.g., ../Pictures/2015_...
files = get_subdirs(pdir_base+'2*')
while 1:

    	# dir of files to move
    #pdb.set_trace()
    rawd = ""
    if os.path.isfile(mv_files):
        rawd = open(mv_files).read()
        rawd = rawd.rstrip('\n')
        ans = input("From - " + rawd + " (y/other):")
    else:
        ans = input("From Directory: ")
    ans = ans.rstrip('\n')
    if ans=='q' or len(ans) < 1:
            break

    # If answer is less than two characters it means (y or carriage return) and that
    # I want to use the directory stored in 'mv_files'.  If not, it is either the
    # full directory path (starts with c:), or a name or partial name of a subdirectory.
    # If multiple subdirectories are found for a partial name, you will be asked to
    # select the correct one.

    # new directory provided
    alist = []
    if len(ans) > 2:
                # see if full path path provided, if so, skip to end of loop and save it
        if 'c:' not in ans:
                # full path not provided, find all match for name provided in subdirectories
            for i in files:
                if ans.lower() in i.lower():
                    alist.append(i)
                # if multiple subdirectories found, ask for the correct one to use.
            if len(alist) > 1:
                j = 1
                for al in alist:
                    print (j, ": ", al)
                    j += 1
                an1 = input ("Enter number: ")
                an1 = an1.rstrip('\n')
                rawd = alist[int(an1)-1] + '/'
            else:
                rawd = alist[0] + '/'

    # write out the current directory path
    #pdb.set_trace()
    outf = open(mv_files, 'w')
    outf.write(rawd)
    outf.close()
    print ('Current directory is: ' + rawd + '\n')
    images={}

    # Now get a list of all the possible files to move, saving the relevant
    # .jpg, .cr2, and photoshop files (.xmp and .psd)
    limages = ls_cmd(None, rawd)
    for im in limages:
        if '.CR2' in im or '.JPG' in im or '.jpg' in im or '.xmp' in im or '.PSD' in im:
            base = im[0:-4]
            if not base in images:
                images[base] = []
            images[base].append(im)
    
    ans = input("Filename to move (all/<name>/<name>:<name>/n): ")
    ans = ans.rstrip('\n')
    #pdb.set_trace()

    keys = list(images.keys())
    keys.sort()

    mdate = ""
    if ans == 'all':
         # move all the appropriate files in the directory
        for afile in keys:
            mdate = get_metdata_date(rawd, images[afile])
            for aa in images[afile]:
                shutil.move(rawd+aa, htdir_base+mdate+'/'+ htdir_end+aa)
                print(rawd+aa, htdir_base+mdate+'/'+htdir_end+aa)
    elif ':' in ans:
            # move a range of appropriate files in the directory
        values = ans.split(':')
        if len(values) > 2:
            print ('Incorrect range for files to move:' + ans)
            exit
                # get rid of any non-numeric characters, convert to int
        start=int(''.join(c for c in values[0] if c in digits))
        end=int(''.join(c for c in values[1] if c in digits))
        for i in keys:
            j = int(''.join(c for c in i if c in digits))
            if j >= start and j <= end:
                mdate = get_metdata_date(rawd, images[i])
                for aa in images[i]:
                    shutil.move(rawd+aa, htdir_base+mdate+'/'+ htdir_end+aa)
                    print(rawd+aa, htdir_base+mdate+'/'+htdir_end+aa)
    else:
            # move one set of appropriate files in the directory
        for afile in keys:
            if ans in afile:
#            #pdb.set_trace()
                mdate = get_metdata_date(rawd, images[afile])
                for aa in images[afile]:
                    shutil.move(rawd+aa, htdir_base+mdate+'/'+ htdir_end+aa)
                    print(rawd+aa, htdir_base+mdate+'/'+htdir_end+aa)
