#!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, unicode_literals, division,
                        print_function)

from maltpynt.mp_lags import mp_lags_from_spectra
from maltpynt.mp_base import mp_root
import logging
import argparse

description = ('Calculate time lags from the cross power spectrum and '
               'the power spectra of the two channels')
parser = argparse.ArgumentParser(description=description)
parser.add_argument("files", help="Three files: the cross spectrum" +
                    " and the two power spectra", nargs='+')
parser.add_argument("-o", "--outroot", type=str, default=None,
                    help='Root of output file names')
parser.add_argument("--loglevel",
                    help=("use given logging level (one between INFO, "
                          "WARNING, ERROR, CRITICAL, DEBUG;"
                          "default:WARNING)"),
                    default='WARNING',
                    type=str)
parser.add_argument("--noclobber", help="Do not overwrite existing files",
                    default=False, action='store_true')
parser.add_argument("--debug", help="use DEBUG logging level",
                    default=False, action='store_true')

if __name__ == '__main__':
    args = parser.parse_args()

    if args.debug:
        args.loglevel = 'DEBUG'

    numeric_level = getattr(logging, args.loglevel.upper(), None)
    logging.basicConfig(filename='MPlags.log', level=numeric_level,
                        filemode='w')

    if len(args.files) != 3:
        raise Exception('Invalid number of arguments')
    cfile, p1file, p2file = args.files

    if args.outroot is None:
        outroot = mp_root(cfile) + '_lag'
    else:
        outroot = args.outroot

    f, df, l, le = mp_lags_from_spectra(cfile, p1file, p2file, outroot=outroot,
                                        noclobber=args.noclobber)
