#!/opt/local/bin/python2.7
import bz2
import cPickle
import imghdr
import os
import sys

import pHash

from image import Image

# Build index
# TODO: write more schtuff here

def main():

    image_list = []

    # Make sure at least one command line argument was provided
    if len(sys.argv) < 2:
        print 'Usage: build_index.py <path>'
        return -1;

    # Print out the path we're walking
    path = sys.argv[1]
    print 'Building image index from path: {:s}\n'.format(path)

    # Walk the root path and count all images
    img_counter = 0
    for root, dirs, files in os.walk(path):
        for file in files:
            img_path = os.path.join(root, file)
            # Check the make sure the file is a JPEG
            if not imghdr.what(img_path) == 'jpeg':
                continue
            img_counter += 1
    print 'Done counting, {:d} images total.'.format(img_counter)

    # Walk the root path
    ctr = 0
    for root, dirs, files in os.walk(path):
        for file in files:
            img_path = os.path.join(root, file)
            # Check the make sure the file is a JPEG
            if not imghdr.what(img_path) == 'jpeg':
                continue
            ctr += 1
            percent_done = int((float(ctr) / img_counter) * 100)
            print '{:3d}% -- {:s}'.format(percent_done, img_path)
            img_obj = Image(img_path)
            # print '{:s} -> {:016X}'.format(img_path, img_obj.hash)
            image_list.append(img_obj)

    # Write index as a bzip2'd file to save space
    index_file = bz2.BZ2File('images_index.bz2', 'w')
    cPickle.dump(image_list, index_file)
    index_file.close()

    print '\nIndex file images_index.bz2 created. Done.'

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