#!/usr/bin/env python3

'''
Command-line tool for parsing PTU files.
'''

import argparse
import json
import logging
import pathlib


from pyptu import PTUParser


LOGGER = logging.getLogger(__name__)


def parse_args(args=None):
    '''
    Parse command-line arguments.

    Args:
        args:
            The arguments. If None, arguments are read from sys.argv.

    Returns:
        The parsed command-line arguments.
    '''
    parser = argparse.ArgumentParser(description='Extract PTU data to standard files.')
    parser.add_argument('path', type=pathlib.Path, help='A path to a PTU file.')
    parser.add_argument('dir', type=pathlib.Path, help='A path to an output directory.')
    return parser.parse_args(args=args)


def main(args=None):
    '''
    Extract data from a PTU file to standard files.

    Args:
        args:
            Passed through to :py:func:`pyptu.__main__.parse_args`.
    '''
    pargs = parse_args(args=args)
    parser = PTUParser(pargs.path)
    parser.load()

    dpath = pargs.dir.resolve()
    dpath.mkdir(parents=True, exist_ok=True)

    with (dpath / 'headers.json').open('w', encoding='utf-8') as handle:
        json.dump(parser.header, handle, indent=True, sort_keys=True)

    parser.photons.to_csv(dpath / 'photons.csv', index=False)
    parser.markers.to_csv(dpath / 'markers.csv', index=False)
    parser.overflows.to_csv(dpath / 'overflows.csv', index=False)


def run_main(args=None):
    '''
    Wrapper around main() with logging configuration and basic error handling.
    '''
    logging.basicConfig(
        style='{',
        format='[{asctime}] {levelname} {message}',
        datefmt='%Y-%m-%d %H:%M:%S',
        level=logging.INFO
    )
    try:
        main(args=args)
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    run_main()
