#!/opt/local/bin/python3

#!/usr/bin/python3

import argparse
import glob
import os
import re
import subprocess
import sys

LEPTON_PATH = '/Users/dsorber/Documents/lepton/lepton'

# Bash text formatting codes
BOLD = '\033[1m'
ENDC = '\033[0m'
RED  = '\033[31m'
YELLOW = '\033[33m'
PURPLE = '\033[35m'

def file_walker(top_path, regex):
    
    files = []
    
    for dirpath, dirnames, filenames in os.walk(top_path):
        for filename in filenames:
            fullpath = os.path.join(dirpath, filename)
            if re.search(regex, fullpath, re.IGNORECASE):
                #~ print(fullpath)
                files.append(fullpath)
        for dirname in dirnames:
            file_walker(os.path.join(dirpath, dirname), regex)
    return files
    
def do_compress(top_path, remove_orig):
    
    # Find all *.jpg (or *.jpeg) images (ignoring case)
    images = file_walker(sys.argv[1], '(\.jpg$)|(\.jpeg$)')
    num_images = len(images)
    
    # Counters to keep track of total compression ratio
    total_uncompressed_bytes = 0
    total_compressed_bytes = 0
    
    print('Found {:d} *.jpg images'.format(num_images))
    
    # Iterate over each image and compress it using the lepton binary
    for idx, image in enumerate(images):
        print('Image {:d} of {:d}:'.format(idx + 1, num_images))
        print('\t{:s}'.format(image))
        
        compressed_image = '{:s}.lep'.format(image)
        cmd = '{:s} "{:s}" "{:s}"'.format(LEPTON_PATH, image, compressed_image)
        #~ rc = subprocess.run(cmd, shell=True)
        #~ if rc.returncode == 0:
        rc = subprocess.call(cmd, shell=True)
        if rc == 0:
            print('{:s}SUCCESS{:s}'.format(BOLD, ENDC))
            total_uncompressed_bytes += os.path.getsize(image)
            total_compressed_bytes += os.path.getsize(compressed_image)
            
            # Only remove original file if specified
            if remove_orig:
                os.remove(image)
        else:
            print('{:s}{:s}ERROR{:s}'.format(BOLD, RED, ENDC))
        print('\n')
    
    # Calculate and print total compression ratio
    percent = (float(total_compressed_bytes) / total_uncompressed_bytes) * 100
    print('Total compression is: {:4.2f}%'.format(percent))
    
def do_decompress(top_path, remove_orig):
    
    # Find all *.lep files (ignoring case)
    images = file_walker(sys.argv[1], '\.lep$')
    num_images = len(images)
    
    print('Found {:d} *.lep files'.format(num_images))
    
    # Iterate over each image and decompress it using the lepton binary
    for idx, image in enumerate(images):
        print('Image {:d} of {:d}:'.format(idx + 1, num_images))
        print('\t{:s}'.format(image))
        
        cmd = '{:s} "{:s}" "{:s}"'.format(LEPTON_PATH, image, image[:-4])
        #~ rc = subprocess.run(cmd, shell=True)
        #~ if rc.returncode == 0:
        rc = subprocess.call(cmd, shell=True)
        if rc == 0:
            print('{:s}SUCCESS{:s}'.format(BOLD, ENDC))
            
            # Only remove original file if specified
            if remove_orig:
                os.remove(image)
        else:
            print('{:s}{:s}ERROR{:s}'.format(BOLD, RED, ENDC))
        print('\n')

def main():
       
    # Make sure the specified path to lepton is correct
    if not (os.path.isfile(LEPTON_PATH) and os.access(LEPTON_PATH, os.X_OK)):
        print('{:s}{:s}ERROR:{:s} unable to find lepton executable'
              .format(BOLD, RED, ENDC))
        return -1

    # Parse command line arguments
    parser = argparse.ArgumentParser(description='Lepton Wrapper')
    
    parser.add_argument('path',
                        help='path in which to look for images')
    
    parser.add_argument('-d', '--decompress', action='store_true', 
                        default=False, help='decompress *.lep files')
                        
    parser.add_argument('-r', '--remove', action='store_true', default=False,
                        help='remove orignal files after compress/decompress')
    
    args = parser.parse_args()

    
    # Either compress or decompress depending on mode parameter
    if args.decompress:
        do_decompress(args.path, args.remove==True)
    else:
        do_compress(args.path, args.remove==True)

    
if __name__ == '__main__':
    sys.exit(main())
