#!python
# -*- coding: utf-8 -*-

# ----------------------------------------------------------------------
# Copyright 2019 Airinnova AB and the FramAT 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

"""
FEMAD

3D finite element analysis
"""

import argparse
import os
import sys

from framat.stdfun import __prog_name__, DEFAULT_MODEL_FILENAME
from framat.__version__ import __version__
from framat.fileio.utils import FileStructure
from framat.stdfun import standard_run, clean_project_dir, __prog_name__
import framat.fem.modelgenerator as mg


def cmd_interface():
    """
    Run FramAT using a command line interface
    """

    # ===== Arguments =====
    parser = argparse.ArgumentParser(prog=f'{__prog_name__}')
    subparsers = parser.add_subparsers(help='execution modes', dest='exec_mode')

    # ----- Mode 'run' -----
    sub = subparsers.add_parser('run', help='run a FEM analysis')
    sub.add_argument('filename', metavar='filename', help='Input file', type=str)
    sub.add_argument('--no-schema-check', action='store_true')
    sub.add_argument('--no-plots', action='store_true', help='do not show any plots')

    group = sub.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')

    group = sub.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')

    # ----- Mode 'example' -----
    sub = subparsers.add_parser('example', help='create an example file')
    sub.add_argument("-o", "--output", help="output file", type=str, default=DEFAULT_MODEL_FILENAME)
    sub.add_argument('-f', '--force', help='overwrite existing file', action='store_true')

    args = parser.parse_args()

    # ----- Mode 'run' -----
    if args.exec_mode == 'run':
        if args.filename:
            if any((args.clean, args.clean_only)):
                clean_project_dir(FileStructure(args.filename))
                if args.clean_only:
                    return
            standard_run(args)

        else:
            parser.print_help()

    # ----- Mode 'example' -----
    elif args.exec_mode == 'example':
        overwrite = args.force
        outfile = args.output

        if os.path.isfile(outfile) and not overwrite:
            print(f"ERROR: File '{outfile}' does already exist.")
            sys.exit(1)

        print(f"Creating file '{outfile}'... ", end='')
        modelobj = mg.get_example('cantilever')
        modelobj.serialise(filename=outfile)
        print("Done!")

    else:
        parser.print_help()


if __name__ == '__main__':
    cmd_interface()
    sys.exit(0)
