#!/usr/bin/env python

import os
import sys
import time
#import datetime

def check_file_creation_time(time_limit, fn):  
      
  if os.path.exists(fn):
    mod_time = os.stat(fn).st_mtime
    print "file modification time %s " % mod_time
    now = time.time()
    print "now time is %s" %now
    print 'time_limit: ' + str(time_limit)
    file_age = now - mod_time
    file_age_str= str(file_age)
    print 'file_age: %s' % file_age_str
  else:
    print "[Exit: Error finding file %s.]\n" %fn
    return 0
          
  if file_age > float(time_limit):
    print "Old enough to be moved\n"
    return 1
  else:
    print 'NOT old enough to be moved yet\n'
    return 0

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 = []

    # Walk the tree.
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = filename
            file_paths.append(filepath)

    return file_paths

def main():
  os.chdir("camera")
  full_file_paths = get_filepaths(".")

  video_wait_time = 660  # 11 min
  picture_wait_time = 30 # 0.5 min

  while 1:
    full_file_paths = get_filepaths(".")

    if full_file_paths:
      print "New files available"
      for f in full_file_paths:
        print f
        if ".jpg" in f:
          wait_time = picture_wait_time
        else:
          wait_time = video_wait_time
        if (check_file_creation_time(wait_time, f) == 1):
          copy_cmd = "..//Dropbox-Uploader//dropbox_uploader.sh upload %s %s" %(f, f)
          print "copy command:"
          print copy_cmd + "\n"
          os.system(copy_cmd)
          os.remove(f)
    else:
      print "NO new files available"

    print "wait for 30s..."
    time.sleep(30)
    
main()

    
