#! /usr/bin/env python

"""Image Grouper.

Usage:
  image-grouper <source_dir> [-o <output_dir>] [-r] [--move] [--exifonly] [-f <format>] [-d]
  image-grouper (-h | --help)
  image-grouper (-v | --version)

Arguments:
  source_dir        path to image source directory

Options:
  -h --help         show this screen
  -v --version      show version
  -o <output_dir>   specify output dir
  -r                read source recursively [default: False]
  --move            move images instead of copying, source will be deleted,
                    use it by caution [default: False]
  --exifonly        read exif only [default: False]
  -f <format>       date format
  -d               show debugging info

"""
from docopt import docopt
import os
from logger import Logger
import exifread

# what tags use to redate file (use first found)
DT_TAGS = ["Image DateTime", "EXIF DateTimeOriginal", "DateTime"]

def readExifDate(image_path):
    """read date from exif, return in format of ('2005:10:20 23:22:28'),
    return None if any error"""
    f = open(image_path, 'rb')
    try:
        tags = exifread.process_file(f, details=False)
        for dt_tag in DT_TAGS:
            try:
                dt_value = '%s' % tags[dt_tag]
                logger.info('%s: %s' % (dt_tag, dt_value))
            except:
                continue

        if dt_value:
            return dt_value
    finally:
        f.close()

    return None


def handleImageByDate(imagePath, date, shouldMove, outputDir):
    pass

if __name__ == '__main__':
    args = docopt(__doc__, version='0.0.1')
    logger = Logger(args['-d'])
    logger.info(args)

    images = []
    for (dirpath, dirnames, filenames) in os.walk(os.path.abspath(args['<source_dir>'])):
        for filename in filenames:
            logger.info(os.sep.join([dirpath, filename]))
            images.extend(os.sep.join([dirpath, filename]))
            date = readExifDate(os.sep.join([dirpath, filename]))
            logger.info(date)

        # no recurse, just top level dir
        if not args['-r']:
            break

@@ -737,16 +737,28 @@
 port os%0A
+import time%0A
 from log
@@ -907,16 +907,53 @@
 eTime%22%5D%0A
+VALID_IMAGE_TYPE = %5B'.jpg', '.JPG'%5D%0A%0A
 %0Adef rea
@@ -1383,16 +1383,20 @@
         
+    
 if dt_va
@@ -1416,23 +1416,42 @@
     
+    
 return 
+exif_info2time(
 dt_value
 %0A   
@@ -1446,16 +1446,17 @@
 dt_value
+)
 %0A    fin
@@ -1506,75 +1506,646 @@
 def 
-handleImageByDate(imagePath, date, shouldMove, outputDir):%0A    pass
+exif_info2time(ts):%0A    %22%22%22changes EXIF date ('2005:10:20 23:22:28') to number of seconds since 1970-01-01%22%22%22%0A    tpl = time.strptime(ts + 'UTC', '%25Y:%25m:%25d %25H:%25M:%25S%25Z')%0A    return time.mktime(tpl)%0A%0A%0Adef calcOutputDirPath(imageFilePath, isExifOnly, outputParentDir):%0A    date = readExifDate(imageFilePath)%0A    if date:%0A        dt = date%0A    elif not isExifOnly:%0A        logger.info('using file last modified time')%0A        dt = os.path.getmtime(imageFilePath)%0A    else:%0A        dt = None%0A%0A    # %25Y-%25m-%25d%0A    targetDirName = time.strftime('%25Y-%25m', time.localtime(dt)) if dt else None%0A    return os.sep.join(%5BoutputParentDir, targetDirName%5D)
 %0A%0Aif
@@ -2272,24 +2272,8 @@
 s)%0A%0A
-    images = %5B%5D%0A
     
@@ -2409,110 +2409,407 @@
     
-logger.info(os.sep.join(%5Bdirpath, filename%5D))%0A            images.extend(os.sep.join(%5Bdirpath, filename
+for ext in VALID_IMAGE_TYPE:%0A                if filename.endswith(ext):%0A                    filepath = os.sep.join(%5Bdirpath, filename%5D)%0A                    logger.info(filepath)%0A                    targetDirName = calcOutputDirPath(filepath, args%5B%0A                                                      '--exifonly'%5D, os.path.abspath(args%5B'-o'%5D) if args%5B'-o'%5D else os.path.abspath(args%5B'%3Csource_dir%3E'
 %5D))%0A
@@ -2824,59 +2824,239 @@
     
+  
-date = readExifDate(os.sep.join(%5Bdirpath, filen
+      logger.info('output dir name is %25s' %25 targetDirName)%0A                    if not args%5B'--move'%5D:%0A                        logger.info('coping image from %25s to %25s' %25%0A                                    (filepath, targetDirN
 ame
-%5D
 ))%0A 
@@ -3070,25 +3070,178 @@
     
-logger.info(date)
+        else:%0A                        logger.info('moving image from %25s to %25s' %25%0A                                    (filepath, targetDirName))%0A%0A                    break
 %0A%0A  

handle output path