#!python
# -*- coding: utf-8 -*
###############################################################################
#                                                                             #
#    LSFM image server                                                        #
#                                                                             #
#    Copyright (C) 2017-2018 Sylwia Bednarek, Piotr Majka                     #
#    (Laboratory of Neuroinformatics; Nencki Institute of Experimental        #
#    Biology of Polish Academy of Sciences)                                   #
#                                                                             #
#    This software is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This software is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this software.  If not, see http://www.gnu.org/licenses/.     #
#                                                                             #
###############################################################################
import os
import json
import glob
import argparse

from lsfmpy import getImageMetaDataClass

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Read relevant metadata from image \
                                                  and dump them in json format',
                                     prog='dump_metadata')

    parser.add_argument('--input-file',
                        required=True,
                        help="Path to the image file",
                        type=str)

    parser.add_argument('--output-file',
                        required=False,
                        default=None,
                        help="Path to output json file",
                        type=str)

    parser.add_argument('--ref',
                        required=False,
                        help="Fill in missing values from another json",
                        default=None,
                        type=str)

    args = parser.parse_args()
    file_path = args.input_file
    meta_data = getImageMetaDataClass(file_path)(file_path)
    ref_path = args.ref

    print meta_data
    print "Please make sure that voxel sizes are in mm."
    if not ref_path:
        fill_in = raw_input("Do you want to fill in missing values now? (y/n) \n")

        if fill_in.lower() == 'y':
            tifs_in_folder = len(glob.glob(os.path.join(os.path.dirname(file_path), '*.tif')))
            print("Found {} tif files in file path".format(tifs_in_folder))
            for k, v in meta_data.iteritems():
                if not v:
                    new_val = raw_input("{}:\n".format(k))
                    meta_data.update({k: float(new_val)})
            meta_data.sanitize_types()

    else:
        with open(ref_path) as fp:
            ref_meta = json.load(fp)
        for k in ['voxel_size_x', 'voxel_size_y', 'voxel_size_z']:
            if not meta_data[k]:
                meta_data.update({k: ref_meta[k]})
            if not meta_data['image_size_z']:
                tifs_in_folder = len(glob.glob(os.path.join(os.path.dirname(file_path), '*.tif')))
                meta_data.update({'image_size_z': int(tifs_in_folder)})

        meta_data.sanitize_types()

    print meta_data

    if args.output_file is not None:
        with open(args.output_file, 'w') as fp:
            json.dump(meta_data, fp)
