#!/usr/bin/env python3

# Copyright (c) 2021, Ericson Joseph
# 
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright notice,
#       this list of conditions and the following disclaimer in the documentation
#       and/or other materials provided with the distribution.
#     * Neither the name of pyMakeTool nor the names of its contributors
#       may be used to endorse or promote products derived from this software
#       without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sys
import signal
import importlib
import argparse
import pkg_resources
from pymakelib import Logger
import shlex

log = Logger.getLogger()

def signal_handler(sig, frame):
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

def get_clazz(generator_path: str):
    return generator_path.split(".")[-1]

def get_module(generator_path: str):
    return generator_path.rsplit('.', 1)[0]

pkgs = [
    'pymakelib.pynewproject_cproject'
]

log.debug("Search pynewproject-* packages installed")

installed_packages = list(pkg_resources.working_set)
for i in installed_packages:
    if str(i.key).startswith("pynewproject"):
        pkgs.append(str(i.key).replace('-', "_"))

log.debug(pkgs)

generator_objs = []

for p in pkgs:
    try:
        mod = importlib.import_module(p)
        generators = getattr(mod, 'generators')
        for g in generators:
            class_name = get_clazz(g)
            module = get_module(g)
            genmod = importlib.import_module("{}.{}".format(p, module))
            clazz = getattr(genmod, class_name)
            obj = clazz()
            generator_objs.append(obj)
    except Exception as ex:
        log.error(ex)

parser = argparse.ArgumentParser()
parser.add_argument('project', help="Project key", nargs='*')
parser.add_argument('-l', '--list', action='store_true', help="List projects availables")
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0.0')
args = parser.parse_args()

def print_projects_availables():
    print("Projects availables:")
    for obj in generator_objs:
        try:
            info = obj.info()
            generator_desc = '' if not 'name' in info else info['desc']
            print(f"  {obj.__class__.__name__:<24}{generator_desc}")
        except Exception as ex:
            log.error(ex)

if args.list:
    print_projects_availables()
    exit(0)

if args.project:
    for obj in generator_objs:
        try:
            if args.project[0] == obj.__class__.__name__:
                log.debug("run exec_generator")
                obj.exec_generator(args=sys.argv[1:]) ## TODO: Check here
                exit(0)
        except Exception as ex:
            log.error(ex)
    print(f"Generator {args.project} not found")
else:
    parser.print_help()
    print("\r")
    print_projects_availables()
