#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import syd
import click
import os
import itk

# -----------------------------------------------------------------------------
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('id', nargs=-1)
@click.option('-k', default=1.1,
              help='Weight parameters to remove scatter : EM-k*Sc')
@click.option('--db', default='',
              help='DB filename (SYD_DB_FILENAME environment variable is used if no filename)')
def syd_geometrical_mean(id, k, db):
    '''
    Compute and insert geometrical mean from ant/post image
    '''

    # open the db
    db_filename = syd.get_db_filename(db)
    db = syd.open_db(db_filename)

    # find all images
    for i in id:
        image = syd.find_one(db['Image'], i)

        # read image
        filepath = syd.get_image_filename(db, image)
        itk_image = itk.imread(filepath)

        # compute gm
        itk_gm = syd.itk_geometrical_mean(itk_image, k)

        # create new image
        tags = ['geometrical_mean']
        output = syd.insert_write_new_image(db, image, itk_gm, tags)

        # print verbose
        f = syd.get_image_filename(db, output)
        p = syd.get_image_patient(db, output)
        print('Inserted image {} {} {} {} {}'
              .format(output['id'], p['name'], output['modality'], f, output['tags']))


# -----------------------------------------------------------------------------
if __name__ == '__main__':
    syd_geometrical_mean()

