#!/usr/bin/env python3
"""
find-duplicates
Desc: A utility that QUICKLY and recursively scans a folder for duplicate files
v.0.1
2020 by radicalarchivist

Usage:
  find-duplicates SCAN-DIR...
  find-duplicates [-o OUTPUT-FILE] SCAN-DIR...
  find-duplicates [-o OUTPUT-FILE] [-x EXTS] SCAN-DIR...
  find-duplicates --help
  find-duplicates --version

Options:
  SCAN-DIR                              Directory to be scanned
  -o --output OUTPUT-FILE               Send output to a csv file
  -x --exclude-extentions EXTS          List of extensions to exclude
  -h --help                             Show this screen
  --version                             Show version info

"""

#
# TODO:
#
# [ ] gui
# [X] exclude extensions
# [ ] exclude directories
#

from docopt import docopt
import time
from dupe_detect import DupeDetector

def print_to_screen(duplicates):
    for dupe in duplicates:
        print(f"{dupe[0]} <==> {dupe[1]}",flush=True)

def save(duplicates,filepath):
    try:
        with open(filepath,"w") as outfile:
            for dupe in duplicates:
                outfile.write(f"{dupe[0]},{dupe[1]}\n")
    except IOError:
        raise

def main(args):
    start_time = time.time()
    detector = DupeDetector(args['SCAN-DIR'],args['--exclude-extentions'],False)
    detector.scan()
    if len(detector):
        print("Duplicates found!",flush=True)
        if args['--output']:
            print(f"Saving output to {args['--output']}",end="...",flush=True)
            try:
                save(detector.duplicates,args['--output'])
                print(f"Done.",flush=True)
            except IOError:
                print("Failed! Do you have the right permissions?",flush=True)
                print("Falling back...",flush=True)
                print_to_screen(detector.duplicates)
        else:
            print_to_screen(detector.duplicates)
    else:
        print("No duplicates found.",flush=True)    
    print(f"Operation completed in {round(time.time() - start_time,2)} seconds.")

if __name__ == "__main__":
    main(docopt(__doc__, version='find-duplicates v.0.1'))