#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# ----------------------------------------------------------------------
# Copyright 2019 Airinnova AB and the PyTornado authors
#
# 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.
# ----------------------------------------------------------------------

# Author: Aaron Dettmann

"""
Command line interface
"""

import argparse

from pytornado.stdfun import standard_run, get_settings, clean_project_dir, __prog_name__
from pytornado.__version__ import __version__
import pytornado.fileio.setup as io_setup


def main():
    """
    TODO
    """

    HELP_SET = "run from a native settings file 'set.*'"
    HELP_WKDIR = "generate a template project directory in-place"
    HELP_CPACS2JSON = "convert a CPACS file to native JSON format"
    # HELP_SETCPACS = "write state to CPACS file from native state file"

    parser = argparse.ArgumentParser(prog=f'{__prog_name__} {__version__}')

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-r', '--run', type=str, help=HELP_SET)
    group.add_argument('--cpacs2json', type=str, help=HELP_CPACS2JSON)
    group.add_argument('--make-wkdir', action='store_true', help=HELP_WKDIR)
    # group.add_argument('--set-cpacs', type=str, nargs=2, help=HELP_SETCPACS)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-v', '--verbose', action='store_true')
    group.add_argument('-d', '--debug', action='store_true')
    group.add_argument('-q', '--quiet', action='store_true')

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-c", "--clean", help="remove old project files", action="store_true")
    group.add_argument("--clean-only", help="clean and exit", action="store_true")
    args = parser.parse_args()

    if args.clean or args.clean_only:
        # TODO: more general way (maybe --run must not be provided)
        if args.run is None:
            raise RuntimeError("Settings file must be specified with '--run'")

        clean_project_dir(get_settings(args.run))

        if args.clean_only:
            return

    if args.run:
        standard_run(args)
    elif args.cpacs2json:
        io_setup.cpacs2pytornado(args.cpacs2json)
    # elif args.set_cpacs:
    #     io_setup.pytornado2cpacs(args.set_cpacs[0], args.set_cpacs[1])
    elif args.make_wkdir:
        io_setup.setup_wkdir()
    else:
        parser.print_help()


if __name__ == '__main__':
    main()
