#!/usr/bin/env python

# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in the
#        documentation and/or other materials provided with the distribution.
#     3. Neither the name of the copyright holder nor the names of
#        its contributors may be used to endorse or promote products
#        derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'''Examples of extracting basic statistics'''
import argparse
import json
import logging
import os
import sys
import yaml
import neurom as nm
from neurom.apps.morph_stats import (extract_stats,
                                     get_header,
                                     generate_flattened_dict)
from neurom.io.utils import get_morph_files
from tqdm import tqdm

L = logging.getLogger(__name__)


_CONFIG = {
    'neurite': {
        'section_lengths': ['max', 'total'],
        'section_volumes': ['total'],
        'section_branch_orders': ['max']
    },
    'neurite_type': ['AXON', 'APICAL_DENDRITE', 'BASAL_DENDRITE', 'ALL'],
    'neuron': {
        'soma_radii': ['mean']
    }
}


def parse_args():
    '''Parse command line arguments'''
    parser = argparse.ArgumentParser(description='Morphology statistics extractor')

    parser.add_argument('datapath',
                        help='Path to a morphology data file or a directory')

    parser.add_argument('-v', '--verbose', action='count', dest='verbose', default=0,
                        help='-v for INFO, -vv for DEBUG')

    parser.add_argument('--as-population',
                        action='store_true',
                        default=False,
                        help='If enabled the directory is treated as a population')

    parser.add_argument('-C', '--config', help='Configuration File')

    parser.add_argument('-o', '--output', dest='output_file',
                        help=('Summary output file name, if it ends in .json, '
                              'a json file is created, if .csv, then a csv file'))

    return parser.parse_args()


def _get_config(config):
    '''Load configuration from file if requested in commandline arge, else use default'''
    if config:
        try:
            with open(config, 'r') as config_file:
                return yaml.load(config_file)
        except yaml.scanner.ScannerError as e:
            L.error('Invalid yaml file : \n %s', str(e))
            sys.exit(1)
    else:
        return _CONFIG


def main(args):
    '''main function'''
    _f = args.datapath
    _results = {}
    _config = _get_config(args.config)

    if os.path.isfile(_f):
        _results[_f] = extract_stats(nm.load_neuron(_f), _config)
    elif os.path.isdir(_f):
        if not args.as_population:
            for _p in tqdm(get_morph_files(_f)):
                _results[_p] = extract_stats(nm.load_neuron(_p), _config)
        else:
            _results[_f] = extract_stats(nm.load_neurons(_f), _config)
    else:
        L.error("Invalid data path %s", _f)
        sys.exit(1)

    if not args.output_file:
        print json.dumps(_results, indent=2, separators=(',', ':'))
    elif args.output_file.endswith('.json'):
        with open(args.output_file, 'w') as output_file:
            json.dump(_results, output_file)
    elif args.output_file.endswith('.csv'):
        import csv
        with open(args.output_file, 'wb') as output_file:
            csvwriter = csv.writer(output_file)
            header = get_header(_results)
            csvwriter.writerow(header)
            for line in generate_flattened_dict(header, dict(_results)):
                csvwriter.writerow(line)


if __name__ == '__main__':
    _args = parse_args()
    logging.basicConfig(level=(logging.WARNING,
                               logging.INFO,
                               logging.DEBUG)[min(_args.verbose, 2)])
    main(_args)
