#!/usr/bin/env python3
"""
Identify groups of images that used exposure-bracketing.

Note that this process may ignore incomplete sequences, where the button was 
not held down long-enough to capture images for the full sequence of exposures, 
unless at least three images were taken (enough to establish a baseline and the 
oscillation/reflectivity of the series).
"""

import sys
import os

_APP_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.insert(0, _APP_PATH)

import logging
import argparse
import json

import bif.exposure_bracketed

_DESCRIPTION = 'Determine groups of exposure-bracketed images.'

def _get_args():
	parser = \
        argparse.ArgumentParser(description=_DESCRIPTION)
	
	parser.add_argument(
        'path',
        help='Path to scan')

	parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='Verbose')

	parser.add_argument(
        '-j', '--json',
        action='store_true',
        dest='print_as_json',
        help='Print as JSON')

	args = parser.parse_args()
	return args

def _main():
	args = _get_args()

	if args.verbose is True:
		logging.basicConfig()
		logging.getLogger().setLevel(logging.DEBUG)

	ba = bif.exposure_bracketed.ExposureBracketedAnalysis()

	bracketed = ba.find_bracketed_images(args.path)

	# Print the results. Sort the results in order to guarantee ordering for 
	# the unit-tests.

	if args.print_as_json is True:
		response = []
		for type_, entries in bracketed:
			entries_info = []
			for hi in entries:
				entries_info.append({
					'rel_filepath': hi.rel_filepath,
					'exposure_value': hi.exposure_value,
					'timestamp': hi.timestamp.isoformat(),
				})

			response.append({
				'type': type_,
				'entries': entries_info,
			})

		response = sorted(response, key=lambda x: [x['type']] + [e['rel_filepath'] for e in x['entries']])

		json.dump(
			response, 
			sys.stdout, 
			sort_keys=True, 
			indent=4, 
			separators=(',', ': '))

		print('')
	else:
		flattened = []
		for type_, entries in bracketed:
			files = [hi.rel_filepath for hi in entries]
			flattened.append((type_, files))

		flattened = sorted(flattened)
		for type_, files in flattened:
			print("{} {}".format(type_, ' '.join(files)))

if __name__ == '__main__':
	_main()
