#!/usr/bin/env python3

import traceback
import argparse
import os,sys
import shutil
import getpass
from pathlib import Path
from settings import config
from importlib import import_module
import re

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

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

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

    args=parser.parse_args()
    
    workdir=os.path.dirname(os.path.abspath(__file__))
    
    # Create directory
    
    path=Path('modules/'+args.path)
    
    try:
        path.mkdir(0o755, True)
        
        open('modules/'+args.path+'/__init__.py', 'a').close()
        
    except:
        
        print('Error: cannot create the directory. Check if exists and if you have permissions')
        exit(1)

    #Create base controller file
    
    #f=open('modules/'+args.path+'/index.py', 'w')
    
    name_module=os.path.basename(args.path)
    
    try:
        shutil.copy(workdir+'/examples/app.py', 'modules/'+args.path)
        
        with open('modules/'+args.path+'/app.py') as f:
            
            app_file=f.read()
        
        app_file=app_file.replace('/example', '/'+name_module)
        
        with open('modules/'+args.path+'/app.py', 'w') as f:
            
            f.write(app_file)
            
            pass

    except:
        
        print('Error: cannot copy controller example. Check if you have permissions')
        exit(1)
    
    # Edit  config.py
    
    #module_final='modules.'+name_module
    module_final=f"'{name_module}': ['modules.{name_module}', '', '']"
    
    try:
    
        with open('./settings/config.py') as f:
            
            #modules_final='\''+'\', \''.join(final_modules)+'\''
            
            p=re.compile(r"^apps=\{(.*)\}$")
            
            #config_file=p.sub(r"modules=[\1, "+modules_final+"]", "modules=['cuchulu.modules.welcome', 'cuchulu.modules.admin', 'cuchulu.modules.lang', 'modules.pastafari', 'modules.monit', 'modules.example']")
            
            final_config=''
            
            for line in f:
                if p.match(line):
                    line=p.sub(r"apps={\1, "+module_final+"}", line)
                final_config+=line
            
        with open('./settings/config.py', 'w') as f:
            
            f.write(final_config)
            
            print('Updated configuration for add new modules...')

    
    except:
        
        print('Cannot update configuration, you need add the new module by hand')
    
    # Reload config
    
    #config.modules.append(module_final)
    
    # Regenerate modules
    
    #regenerate_modules_config()

def regenerate_modules_config():
    
    print("Regenerating modules configuration...")
    
    modules=[]
    
    modules.append("#!/usr/bin/env python3\n\n")
    modules.append("list_modules=[]\n\n")
    
    for module in config.modules:
    
        try:
            
            controller_path=import_module(module)
            
            controller_base=os.path.dirname(controller_path.__file__)
            
            base_module=module.split('.')[-1]
            
            dir_controllers=os.listdir(controller_base)
            
            modules.append('from '+module+' import ')
            
            arr_controllers=[]
            
            for controller in dir_controllers:
                
                if controller.find('.py')!=-1 and controller.find('_')==-1:
                    
                    controller_py=controller.replace('.py', '')
                    
                    arr_controllers.append(controller_py)
                    
                    #load(module+'.'+controller_py)


            modules.append(", ".join(arr_controllers))

            modules.append("\n\n")

            #add_func_static_module(controller_base)
            
        except:
            
            print("Exception in user code:")
            print("-"*60)
            traceback.print_exc(file=sys.stdout)
            print("-"*60)
            exit(1)
    
    with open('./settings/modules.py', 'w') as f:
        f.write("".join(modules))

if __name__=="__main__":
    start()
