#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
#   Copyright 2016-2021 Blaise Frederick
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
#
import argparse

import numpy as np

import rapidtide.io as tide_io
import rapidtide.stats as tide_stats
import rapidtide.workflows.parser_funcs as pf


def _get_parser():
    """
    Argument parser for histtc
    """
    parser = argparse.ArgumentParser(
        prog="histtc",
        description=("Generate a histogram of the values in a timecourse"),
        usage="%(prog)s inputfile outputroot [--numbins BINS]",
    )

    # Required arguments
    pf.addreqinputtextfile(parser, "inputfilename", onecol=True)
    pf.addreqoutputtextfile(parser, "outputroot")

    # add optional arguments
    parser.add_argument(
        "--numbins",
        dest="histlen",
        action="store",
        type=int,
        metavar="BINS",
        help=("Number of histogram bins (default is 101)"),
        default=101,
    )
    return parser


def main():
    # grab the command line arguments then pass them off.
    try:
        args = _get_parser().parse_args()
    except SystemExit:
        _get_parser().print_help()
        raise

    dummy, dummy, colnames, inputdata, compressed, filetype = tide_io.readvectorsfromtextfile(
        args.inputfilename
    )

    maxval = np.max(inputdata)
    minval = np.min(inputdata)
    therange = [minval, maxval]
    print("therange:", therange)

    tide_stats.makeandsavehistogram(inputdata, args.histlen, 0, args.outputroot, therange=therange)


if __name__ == "__main__":
    main()
