#!/usr/bin/env python
"""Creates an Eve-based API project.

Usage:
    mkapi [-h|--help] [-d|--with_docker] [-v|--with_val] [-a|--with_auth] [-w|--with_web_socket] api_name

Examples:
    mkapi my-api
    mkapi my-api --with-docker

License:
    MIT License

    Copyright (c) 2021 Michael Ottoson

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
"""

import os
import sys
import argparse
from distutils.dir_util import copy_tree, remove_tree

import importlib
import eve_utils


def import_path(path):
    module_name = os.path.basename(path).replace('-', '_')
    spec = importlib.util.spec_from_loader(
        module_name,
        importlib.machinery.SourceFileLoader(module_name, path)
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    sys.modules[module_name] = module
    return module


def remove_if_exists(folder):
    if os.path.exists(folder):
        remove_tree(folder)


def make_api(project_name):  # TODO: refactor with eve_utils.copy_skel()?
    print(f'Creating {project_name} api')

    skel = os.path.join(os.path.dirname(eve_utils.__file__), 'skel/api')

    os.mkdir(project_name)  # TODO: ensure doesn't already exist, etc
    copy_tree(skel, project_name)

    # TODO: can the following remove_tree calls be obviated if skel is packaged differently?
    remove_if_exists(os.path.join(project_name, '__pycache__'))
    remove_if_exists(os.path.join(project_name, 'configuration', '__pycache__'))
    remove_if_exists(os.path.join(project_name, 'domain', '__pycache__'))
    remove_if_exists(os.path.join(project_name, 'hooks', '__pycache__'))
    remove_if_exists(os.path.join(project_name, 'log_trace', '__pycache__'))
    remove_if_exists(os.path.join(project_name, 'utils', '__pycache__'))

    eve_utils.replace_project_name(project_name)


def main():
    parser = argparse.ArgumentParser('mkapi', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('api_name', help='The name of the API to create.')
    parser.add_argument('-d', '--with_docker', help='add Dockerfile and supporting files to deploy the API as a container', action='store_true')
    parser.add_argument('-v', '--with_val', help='add custom validation class', action='store_true')
    parser.add_argument('-a', '--with_auth', help='add authorization class and supporting files', action='store_true')
    parser.add_argument('-s', '--with_serverless', help='add serverless framework and supporting files', action='store_true')
    parser.add_argument('-w', '--with_web_socket', help='add web socket and supporting files', action='store_true')

    args = parser.parse_args()
    project_name = args.api_name  # TODO: validate, safe name, etc.
    make_api(project_name)

    if args.with_docker:
        add_docker_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'add_docker')
        ad = import_path(add_docker_path)
        ad.add_docker(project_name)

    if args.with_val:
        add_val_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'add_val')
        ad = import_path(add_val_path)
        cur = os.getcwd()
        os.chdir(project_name)
        ad.add_validation()
        os.chdir(cur)

    if args.with_auth:
        add_auth_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'add_auth')
        ad = import_path(add_auth_path)
        cur = os.getcwd()
        os.chdir(project_name)
        ad.add_authorization()
        os.chdir(cur)

    if args.with_serverless:
        add_serverless_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'add_serverless')
        ad = import_path(add_serverless_path)
        ad.add_serverless(project_name)

    if args.with_web_socket:
        add_web_socket = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'add_web_socket')
        ad = import_path(add_web_socket)
        cur = os.getcwd()
        os.chdir(project_name)
        ad.add_web_socket()
        os.chdir(cur)

    print('Please run these two commands')
    print(f'  cd {project_name}')
    print('  pip install -r requirements.txt')

if __name__ == '__main__':
    main()
