#!/usr/bin/env python3

import traceback
import argparse
import os,sys
import shutil
import getpass
from pathlib import Path
from importlib import import_module
from cuchulu.libraries.slugify import slugify
import json

sys.path.insert(0, os.path.realpath('.'))

try:

    from settings import config
    from settings import modules
    
except:
    
    pass
        

def start():
    """Module for create new modules for cuchulu
    """

    parser=argparse.ArgumentParser(description='A tool for create new modules for cuchulu')

    parser.add_argument('--folder', help='The folder where the new cuchulu module is located', required=True)

    args=parser.parse_args()
    
    workdir=os.path.dirname(os.path.abspath(__file__))
    
    # Create directory
    
    real_path=os.path.basename(slugify(args.folder))
    
    path=Path('modules/'+real_path)
    

    path.mkdir(0o755, True)
    
    #open('modules/'+args.path+'/__init__.py', 'a').close()
    with open('modules/'+real_path+'/__init__.py', 'a') as f:
        f.write("from bottle import Bottle\n\n")
        f.write("{}_app=Bottle()\n\n".format(real_path, real_path))
                
    with open('modules/'+real_path+'/app.py', 'w') as f:
        
        f.write("from modules.{} import {}_app\n\n".format(real_path, real_path))
        f.write("@{}_app.route('/{}')\n\n".format(real_path, real_path))
        f.write("def {}_home():\n".format(real_path, real_path))
        f.write("    return {'hello': 'world'}")

        
        with open('settings/modules.py', 'a') as f:
            
            if not real_path in modules.extra_apps:
                #modules.extra_apps[real_path]=['modules.{}'.format(real_path), '{}_app'.format(real_path), '/']
                f.write("extra_apps['{}']=['modules.{}', '{}_app', '/']".format(real_path, real_path, real_path))

    print('Created the new module. Please, reload the WSGI server if not reload automatically and go to url /'+real_path)
    
if __name__=="__main__":
    start()
