#!/usr/bin/env python

import os
import sys
import argparse
import logging
from tofu import config


LOG = logging.getLogger(__name__)


def init(args):
    if not os.path.exists(config.NAME):
        config.write(args.config)
    else:
        sys.exit("{0} already exists".format(config.NAME))


def run_tomo(args):
    from tofu import reco
    reco.tomo(args)


def run_lamino(args):
    from tofu import reco
    reco.lamino(args)


def gui(args):
    from tofu import gui
    gui.main(args)


def estimate(params):
    from tofu import reco
    center = reco.estimate_center(params)
    if params.verbose:
        out = '>>> Best axis of rotation: {}'.format(center)
    else:
        out = center

    print(out)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', **config.SECTIONS['general']['config'])
    subparsers = parser.add_subparsers(title="Commands", metavar='')

    # init parser
    cmd_parser = subparsers.add_parser('init', help="Create a configuration file")
    cmd_parser.add_argument('--verbose', **config.SECTIONS['general']['verbose'])
    cmd_parser.set_defaults(_func=init)

    # tomo parser
    tomo_params = config.TomoParams()
    tomo_parser = subparsers.add_parser('tomo', help="Run tomographic reconstruction")
    tomo_parser = tomo_params.add_arguments(tomo_parser)
    tomo_parser.set_defaults(_func=run_tomo)

    # gui parser
    gui_params = config.TomoParams(sections=('gui',))
    gui_parser = subparsers.add_parser('gui', help="GUI for tomographic reconstruction")
    gui_parser = gui_params.add_arguments(gui_parser)
    gui_parser.set_defaults(_func=gui)

    # lamino parser
    lamino_params = config.LaminoParams()
    lamino_parser = subparsers.add_parser('lamino', help="Run laminographic reconstruction")
    lamino_parser = lamino_params.add_arguments(lamino_parser)
    lamino_parser.set_defaults(_func=run_lamino)

    # estimate parser
    estimate_params = config.TomoParams(sections=('estimate',))
    estimate_parser = subparsers.add_parser('estimate', help="Estimate center of rotation")
    estimate_parser = estimate_params.add_arguments(estimate_parser)
    estimate_parser.set_defaults(_func=estimate)

    args = config.parse_known_args(parser, subparser=True)

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    args._func(args)


if __name__ == '__main__':
    main()

# vim: ft=python
