#! /usr/bin/env python
__author__ = "henthorn"
__copyright__ = "2024, MBARI"
__credits__ = ["MBARI"]
__license__ = "GPL-3.0"
__maintainer__ = "henthorn"
__email__ = "henthorn at mbari.org"
__doc__ = '''

SES Image Processing (sip) attenuation script.

This application was derived from a script written by Crissy Huffard that
processes a folder of SES JPG images producing a CSV file of attenuation
values for each image. That script was then modified to allow attenuation
to be measured one image at a time, although multiple images can be processed
with a single run.

The data used to calculate the average background of the last 20 images is
cached in a pickle file for use the next time the script is run.

@author: __henthorn__
@license: __license__
'''

import datetime
import logging
import argparse
import pickle
import sip

# Attenuation max greater than any normally observed value
MAX_ATN = 4.0

def main():
    args = argparse.ArgumentParser(description = 'SIP cache background accumulator')
    args.add_argument('-n', '--bg_num', default=20, type=int, help='Number of background images to cache')
    args.add_argument('-d', '--db_file', default="./sip_bg_cache.p", type=str, help='Background image cache')
    args.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
    args.add_argument('jpgfiles', nargs='+', help='Input image file')

    args = args.parse_args()
    if (args.verbose):
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    else:
        logging.basicConfig(level=logging.CRITICAL, format='%(asctime)s - %(levelname)s - %(message)s')

    # Load cached background if it exists
    try:
        with open(args.db_file, 'rb') as f:
            logging.debug('Begin loading background cache: ' + args.db_file)
            bg = pickle.load(f)
            logging.debug('Done loading background cache')
    except FileNotFoundError:
        bg = sip.SIP_bg_accumulator(args.bg_num)
        logging.debug('New cache created: ' + args.db_file + ' for ' + str(args.bg_num) + ' images')
    else:
        logging.debug('Loaded cached background with ' + str(bg.num_images) + ' images')

    # Process image files in argument list
    for imgfile in args.jpgfiles:
        emit = None
        try:
            logging.debug('Begin processing ' + imgfile)
            s = sip.SIP_image(imgfile)
            s.normalize()
            if (bg.num_images == bg.max_images):
                s.measure_atn(bg.circle_mask(), bg.avg_bg)
                # Attenuation occasionally results in a value of 'inf'
                # In those cases we will set the atn to a high value
                if (float('inf') == s.attenuation):
                    s.attenuation = MAX_ATN

                logging.debug('Done processing ' + imgfile)
                emit = f"{imgfile} , {s.attenuation} , {bg.num_images}"

            logging.debug('Begin accumulating ' + imgfile)
            bg.acc(imgfile, s.photo_norm)
            logging.debug('Done accumulating into cache with ' + str(bg.num_images) + ' images')
        except:
            logging.info('sip_attenuation.py: Unable to process image: ' + imgfile)
            emit = None

        if (emit is not None):
            ct = datetime.datetime.now()
            print(f"{ct}, {emit}")


    with open(args.db_file, 'wb') as f:
        logging.debug('Saving and closing ' + args.db_file)
        pickle.dump(bg, f)

    logging.debug('Done!')
    return

if __name__ == "__main__":
    main()

