#! /usr/bin/python3 -s

# 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 basic data checks."""
import argparse
import json
import logging
import sys
from pathlib import Path

import pkg_resources
from neurom.apps import get_config
from neurom.check.runner import CheckRunner
from neurom.exceptions import ConfigError

CONFIG_PATH = pkg_resources.resource_filename('neurom', 'config')

DESCRIPTION = """
NeuroM Morphology Checker
=========================
"""

EPILOG = """
Description
-----------

Performs checks on reconstructed morphologies from data contained in
morphology files.

The tests are performed in four steps:

1. Files are loaded into an intermediary "raw data" format. If this fails, the
tests for that particular file are aborted. Reasons for failure can include
structural issues that are too difficult to recover from.

2. Structural tests are carried out. Failure in some of these may make further
tests fail.

3. A neuron object is built from the data loaded in 1. Failure at this stage
results in further tests for this particular file being aborted.

4. Soma and neurite tests are performed.

It is very likely that a failure in the structural tests will make the neurite
and soma tests fail. Furthermore, inability to build a soma typically results
in an inability to build neurites. Failure to build a soma or neurites results
in an early faulure for a given morphology file.

Default checked errors
----------------------
* Not a single tree structure
* No soma points detectes
* Missing parents
* IDs not in increasing order
* IDs not sequential
* No soma could be reconstructed
* No neurites could be reconstructed
* Zero radius soma
* No axon
* No apical dendrite
* No basal dendrite
* Zero radius points
* Zero length segments
* Zero length sections

Default values for options
--------------------------
* has_nonzero_soma_radius 0.0
* has_all_nonzero_neurite_radii: 0.007
* has_all_nonzero_segment_lengths: 0.01
* has_all_nonzero_section_lengths: 0.01

Available Checks
----------------
                      Options
has_no_jumps:         has_no_jumps - default 30 micrometer
                                     distance considered a jump
                      axis - default 'z', which axis to check
has_no_narrow_starts: fraction_smaller - default 0.9 - difference between first
                      and second trunk segment points

Examples
--------
morph_check --help               # print this help
morph_check some/path/neuron.h5  # Process an HDF5 file
morph_check some/path/neuron.swc # Process an SWC file
morph_check some/path/           # Process all HDF5 and SWC files found in directory
"""

L = logging.getLogger(__name__)


def _setup_logging(debug, log_file):
    """ Set up logger """

    fmt = logging.Formatter('%(levelname)s: %(message)s')

    level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(level=level)
    log = logging.getLogger()
    log.handlers[0].setFormatter(fmt)

    if log_file:
        handler = logging.FileHandler(log_file)
        handler.setFormatter(fmt)
        log = logging.getLogger()
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description=DESCRIPTION,
                                     formatter_class=argparse.RawTextHelpFormatter,
                                     epilog=EPILOG)
    parser.add_argument('datapath',
                        help='Path to morphology data file or directory')

    parser.add_argument('-d', '--debug',
                        action='store_true',
                        help="Log DEBUG information")

    parser.add_argument('-l', '--log', dest='log_file',
                        default="", help="File to log to")

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

    parser.add_argument('-o', '--output', dest='output_file',
                        default='summary.json', help='Summary output file name')

    return parser.parse_args()


def main(args):
    """Run all the checks."""
    _setup_logging(args.debug, args.log_file)

    try:
        config = get_config(args.config, Path(CONFIG_PATH, 'morph_check.yaml'))
        checker = CheckRunner(config)
    except ConfigError as e:
        L.error(str(e))
        sys.exit(1)

    summary = checker.run(args.datapath)

    with open(args.output_file, 'w') as json_output:
        json.dump(summary, json_output, indent=4)

    return 0 if summary['STATUS'] == 'PASS' else 1


if __name__ == '__main__':
    sys.exit(main(parse_args()))
