#! /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
from pathlib import Path
import sys

from neurom.check import structural_checks as st_chk
from neurom.io.utils import get_morph_files
from neurom.io import load_data

DESCRIPTION = """
NeuroM Raw Data Checker
=======================
"""

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

Performs basic checks on raw data contained in morphology files.
There is no processing performed to the data prior to checks.

Note: these checks are designed to capture significant problems in data. They
do not impose refined semantic constraints, but rather check for missing or
inconsistent data which would render further processing unreliable or even
impossible.

Errors checked for
------------------
* No soma points
* Non-consecutive point IDs

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


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')

    return parser.parse_args()


def run(args):
    """Check if all files have a soma points and sequential ids."""
    data_path = Path(args.datapath)
    if data_path.is_file():
        files = [data_path]
    elif data_path.is_dir():
        print('Checking files in directory', data_path)
        files = get_morph_files(data_path)
    else:
        sys.exit('ERROR: Invalid data path %s' % data_path)

    for f in files:
        raw_data = load_data(f)
        print('\nCheck file %s...' % f)
        print('Has soma points? %s' % st_chk.has_soma_points(raw_data))

        result = st_chk.has_sequential_ids(raw_data)
        print('Consecutive indices? {}'.format(result.status))
        if not result.status:
            print('Non consecutive IDs detected: {}'.format(result.info))


if __name__ == '__main__':
    run(parse_args())
