#!/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
import subprocess
#from colorama import init, Fore, Back, Style
import colorama

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 paramecio
    """

    parser=argparse.ArgumentParser(description='A tool for add modules for paramecio from git url')

    parser.add_argument('--git_url', help='The git url for clone the module.', required=True)

    args=parser.parse_args()
    
    colorama.init()
    
    workdir='.'
    
    os.chdir('./modules/')
    
    if subprocess.call("git clone {}".format(args.git_url), shell=True) > 0:
        print('Error, cannot install the git module. Do you have installed git?. Is a correct url?')
        exit(1)    
        
    real_path=''
    
    with os.scandir('.') as d:
        for e in d:
            #print(e.name)
            if not e.name in config.apps:
                #print(e.name)
                if args.git_url.find(e.name)!=-1:
                    real_path=os.path.basename(e.name)
    
    # Add dependencies using pip
    
    os.chdir('../')
    
    dependencies_file='./modules/{}/dependencies.json'.format(real_path)
    
    if os.path.isfile(dependencies_file):
        
        dep_json=[]
        
        with open(dependencies_file) as f:
            
            content=f.read()
            
            try:
                dep_json=json.loads(content)
            except:
                dep_json=[]
                print('Error: cannot install dependencies for the package. Malformed json {}'.format(content))
        
        if len(dep_json)>0:
            if 'packages' in dep_json:
                print('Install dependencies for the module...')
                arr_packages=" ".join(dep_json['packages'])
                if subprocess.call("pip install {}".format(arr_packages), shell=True) > 0:
                    print('Error, cannot install the pip libraries. Do you have installed pip?.')
            
            if 'models' in dep_json:
                print('Creating database tables from models in module...')
                for model in dep_json['models']:
                    if subprocess.call("cuchuludb --model modules/{}/models/{}.py".format(real_path, model), shell=True) > 0:
                        
                        print('Error, cannot install the model {}.'.format(model))
    
    # Add to json configuration. 
    
    if real_path!='':
        """
        if os.path.isfile('settings/modules.json'):
            
            modules_json={}
            
            with open('settings/modules.json') as f:
                print('Inserting new module in modules.json...')
                
                json_text=f.read()
                
                if json_text!='':
                    modules_json=json.loads(json_text)
        
            with open('settings/modules.json', 'w+') as f:
                modules_json[real_path]=['modules.'+real_path, real_path+'_app', '/']
                
                f.write(json.dumps(modules_json, indent=4))

        """
        
        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('Please, reload your wsgi application for access to your new module if you don\'t have autoreload enabled')

if __name__=="__main__":
    start()
