#!/usr/bin/env python
# Python binary for creating workdirs.

import argparse
import importlib
import os
from os import path

import yaml
from shutil import copyfile

import moon_automation.Modules as Mod

testbed_example = {'devices': {'R1': {'connections': {'cli': {'ip': '1.1.1.1', 'port': 22, 'protocol': 'ssh'}},
                                      'credentials': {'default': {'password': 'cisco', 'username': 'cisco'}},
                                      'os': 'iosxr', 'type': 'iosxr'},
                               'R2': {'connections': {'cli': {'ip': '2.2.2.2', 'port': 23, 'protocol': 'telnet'}},
                                      'credentials': {'default': {'password': 'cisco', 'username': 'cisco'}},
                                      'os': 'nxos', 'type': 'nxos'}}}


def load(fp):
    with open(fp) as f:
        config = yaml.load(f.read())
        return config

def get_installed_modules():
    files = os.listdir(Mod.__path__[0])
    modules=[]
    for module in files:
        if os.path.isdir(os.path.join(os.path.abspath(Mod.__path__[0]), module)) and "__" not in module:
            modules.append(module)
    return modules

def import_class(module_name, class_name):
    try:
        # Try if module exists in current workdir (for override)
        # Otherwise load from automation lib
        m = importlib.import_module("{}.{}".format(module_name, class_name))
        # get the class, will raise AttributeError if class cannot be found
        return getattr(m, class_name)
    except:
        pass
    try:
        # load the module, will raise ImportError if module cannot be loaded
        m = importlib.import_module("moon_automation.{}.{}".format(module_name, class_name))
        # get the class, will raise AttributeError if class cannot be found
        return getattr(m, class_name)
    except Exception as e:
        raise Exception("Module {} not valid".format(module_name))



if __name__ == '__main__':
    # Create folders
    parser = argparse.ArgumentParser(description='Moon Automation Project init tool.')
    parser.add_argument('-a','--add-task', nargs='+',
                        help='Add tasks to automation project. Example: moon-init -a ExampleModule BackupConfigModule', required=False)
    parser.add_argument('--show-modules',
                        help='Show all installed modules',required=False,action='store_true')

    args = parser.parse_args()
    if args.show_modules:
        print("Current installed modules:")
        modules=os.listdir(Mod.__path__[0])
        for module in modules:
            if os.path.isdir(os.path.join(os.path.abspath(Mod.__path__[0]), module)) and "__" not in module:
                print(module)
        exit(0)
    elif args.add_task:
        if not path.exists("config.yaml"):
            print("config.yaml not found.")
            exit(0)
        else:
            with open("config.yaml", "r") as file:
                config = yaml.load(file.read())
            modules=get_installed_modules()
            for task in args.add_task:
                if task in modules:
                    # Copy config file
                    example_config_path = os.path.join(os.path.abspath(Mod.__path__[0]), task,"config.yaml")
                    dest_config_path = os.path.join(os.path.abspath("."),"Tasks","{}.yaml".format(len(config["tasks"])+1))
                    copyfile(example_config_path,dest_config_path)
                    config["tasks"].append({task:{"config":os.path.join("Tasks","{}.yaml".format(len(config["tasks"])+1))}})
                    print("Task {} added".format(task))
            with open("config.yaml", "w+") as file:
                file.write(yaml.dump(config, default_flow_style=False))
            print("config.yaml updated")
        exit(0)

    print("Start initiating environment...")

    print("Creating Tasks folder for task configurations...", end='')
    try:
        os.makedirs("Tasks")
        print("Done")
    except FileExistsError:
        print("Already Exist,Skipping")

    print("Creating outputs folder for outputs from test...", end='')
    try:
        os.makedirs("outputs")
        print("Done")
    except FileExistsError:
        print("Already Exist,Skipping")

    print("Creating config.yaml...", end='')
    if path.exists("config.yaml"):
        print("Already Exist,Skipping")
    else:
        with open("config.yaml", "w+") as file:
            file.write(yaml.dump({"topology": "testbed.yaml", "tasks": []}))
        print("Done")

    print("Creating testbed.yaml...", end='')
    if path.exists("testbed.yaml"):
        print("Already Exist,Skipping")
    else:
        with open("testbed.yaml", "w+") as file:
            file.write(yaml.dump(testbed_example))
        print("Done")

    print("All Done,Exiting.")
    exit(0)
