#!/usr/bin/python3

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

LEPTON_PATH = '/home/dsorber/devasdf/lepton/lepton'

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

def image_walker(top):
    
    images = []
    
    for dirpath, dirnames, filenames in os.walk(top):
        for filename in filenames:
            fullpath = os.path.join(dirpath, filename)
            if re.search('(\.jpg$)|(\.jpeg$)', fullpath, re.IGNORECASE):
                #~ print(fullpath)
                images.append(fullpath)
        for dirname in dirnames:
            image_walker(os.path.join(dirpath, dirname))
    return images

def main():
    
    if len(sys.argv) < 2:
        print('{:s}{:s}ERROR:{:s} you must supply a path'.format(BOLD, RED, ENDC))
        return -1
    
    # 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

    #~ parser = argparse.ArgumentParser(description='Ryft Package Build Script')
    
    #~ parser.add_argument('-ni', '--non-interactive', default=False, 
                        #~ action='store_true', 
                        #~ help='non-interactive mode; do not prompt user for input')
    #~ parser.add_argument('-pn', '--package', default=None, 
                        #~ type=validate_package_name,
                        #~ help='the name of the package to build')
    #~ parser.add_argument('-pv', '--pkg-version', default=None, 
                        #~ type=validate_version_argparse,
                        #~ help='the new version of the package')

    images = image_walker(sys.argv[1])
    num_images = len(images)
    
    total_uncompressed_bytes = 0
    total_compressed_bytes = 0
    
    print('Found {:d} *.jpg images'.format(num_images))
    
    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:
            print('{:s}SUCCESS{:s}'.format(BOLD, ENDC))
            total_uncompressed_bytes += os.path.getsize(image)
            total_compressed_bytes += os.path.getsize(compressed_image)
        else:
            print('{:s}{:s}ERROR{:s}'.format(BOLD, RED, ENDC))
        print('\n')
        
    percent = (float(total_compressed_bytes) / total_uncompressed_bytes) * 100
    print('Total compression is: {:4.2f}%'.format(percent))
    
if __name__ == '__main__':
    sys.exit(main())
