#!/python/bin

import glob
import os, fnmatch
import argparse
import shutil
import sys

# Changed _configuration to _config in f.find
# section in order to handle files using either
# converntion.
#
# Added _shutters to f.find
# section to handle these files.
#
# Added _dich to f.find section
# to handle the dichroic files.
# M. McMaster  09/14/2016
#
# Added _trace to f.find section
# to handle these files, which
# go in the wavepix directory
# M. McMaster 09/27/2016
# 
# Changed code to exit with error if the configuration files have name
# _config_ as these files should be _configuration_
# R. Diaz 9/27/2016
#
# Changed to move the section for _trans_ under the section for _dich_ because
# all the dichroic files, regardles they being _trans_ should go in the optical
# directory. According to Tim Pickering
# Also added a section to move the _wl files to the optical/ directory. This 
# affects NIRCam files.
# October 5 2016


def find_pattern(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

def parse_args():

    '''
    Parse command line arguments

         --filename is the name of the file to move
         --directory is the target directory where to move the file
         --detector
    '''

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--filename', action='store', dest='filename',\
            default='*.fits')
    parser.add_argument('-d', '--directory', action='store', dest='directory',\
            default='*.fits')
    parser.add_argument('-t', '--detector', action='store', dest='detector',\
            default='*.fits')
    args = parser.parse_args()
    return args

if __name__ == '__main__':

    args = parse_args()

    ua=args.filename
    if ua == '':
        ua='*.fits'
    else:
        files = glob.glob(ua)

    fout=open('results_mv_files.txt','w')

    for f in files:
        l=f.find('.fits')
        j=f.find('.json')
        dirfile =''
        if f.find('_disp') > 0:
            dirfile = '/dispersion/'
        elif f.find('_blaze') > 0:
             dirfile = '/blaze/'
        elif f.find('_optical') > 0:
             dirfile = '/optical/'
        elif f.find('_dich') > 0:
             dirfile = '/optical/'
        elif f.find('_trans_modmean') > 0i or f.find('_substrate_trans'):
	     dirfile('/optical/')
        elif f.find('_trans') > 0:
             dirfile = '/filters/'
        elif f.find('_psf') > 0:
             dirfile = '/psfs/'
        elif f.find('_r.') > 0:
             dirfile = '/resolving_power/'
        elif f.find('_ldwave') > 0:
             dirfile = '/wavecal/'
        elif f.find('_specef') > 0:
             dirfile = '/blaze/'
        elif f.find('_ipc') > 0:
             dirfile = '/detector/'
        elif f.find('_qe') > 0:
             dirfile = '/qe/'
        elif f.find('_throughput') > 0:
             dirfile = '/optical/'
        elif f.find('_telescope') > 0:
             dirfile = '/'
        elif f.find('_config_') > 0:
             print('_config_ file is not a valid file. Change it to _configuration_')
	     sys.exit(0)
        elif f.find('_configuration') > 0:
             dirfile = '/'
       
        elif f.find('_shutters') > 0:
             dirfile = '/'
        elif f.find('_internaloptics') > 0:
             dirfile = '/optical/'
        elif f.find('_lyot') > 0:
             dirfile = '/optical/'
        elif f.find('_substrate') > 0:
             dirfile = '/optical/'
        elif f.find('_dbs_') > 0:
             dirfile = '/optical/'
        elif f.find('_trace') > 0:
             dirfile = '/wavepix/'
        elif f.find('_wl') > 0:
             dirfile = '/optical/'
        loc_dir=args.directory+args.detector+dirfile
        if len(dirfile) > 0:
            loc_dir=args.directory+args.detector+dirfile
            lf = len(f)
            f_old = f[0:lf-19]+'*'
            f_old_rm=find_pattern(f_old,loc_dir)
            if len(f_old_rm) > 0:
                try:
                  os.remove(f_old_rm[0])
                  fout.write("removed file "+ f_old_rm[0])
                  print "removed file ", f_old_rm[0]
                except OSError:
                  fout.write("Couldnt remove file " + f_old_rm[0])
                  print "Couldnt remove file " , f_old_rm[0]
            print 'Copying file ',f, 'to directory ', loc_dir
            fout.write('Copying file '+f+ 'to directory ' + loc_dir)
            shutil.copy(f,loc_dir+f)


