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

import syd
import click

# -----------------------------------------------------------------------------
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('dicomseries', nargs=-1)
@click.option('--label', default=[], multiple=True,
              help='Add a label')
@click.option('--db', default='',
              help='DB filename (SYD_DB_FILENAME environment variable is used if no filename)')
def syd_insert_image_from_dicom(dicomseries, label, db):
    '''
    Convert dicom image to mhd image.

    DICOMSERIES : list of DicomSerie ids
    '''

    # check input
    dicomseries = syd.parse_piped_input(dicomseries)
    if len(dicomseries) == 0:
        syd.fatal('Please provide at least one id.')

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

    # get the dicom_series
    dicom_series = syd.find(db['DicomSeries'], id=dicomseries)

    # look and insert dicom
    for dicom_serie in dicom_series:
        im = syd.insert_image_from_dicom(db, dicom_serie)
        if im == None:
            continue
        if len(label) != 0:
            syd.add_labels(im, label)
            syd.update_one(db['Image'], im)
        p = syd.get_image_patient(db, im)
        f = syd.get_image_filename(db, im)
        print('Inserted image {} {} {} {} from dicom {}'
              .format(im['id'], p['name'], im['modality'], f, dicom_serie['id']))

    if len(dicom_series) == 0:
        print('No dicom series found with id {}.'.format(dicomseries))

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

