#!/usr/bin/python

import sys, os

_path = os.path.abspath(os.path.join(os.path.dirname(__file__),"."))
if _path not in (os.path.abspath(p) for p in sys.path):
    sys.path[1:1] = [_path]

def set_prompt(prompt="SOLO"):
    sys.ps1 = prompt + "> "
    sys.ps2 = prompt + ". "
    try:
        ip=sys.modules["__main__"].__dict__["get_ipython"]()
        from IPython.terminal.prompts import Prompts, Token
        class soloprompts(Prompts):
            def in_prompt_tokens(self, *wtf):
                return [(Token.Prompt, prompt+'> ')]
            def continuation_prompt_tokens(self, *wtf):
                return [(Token.Prompt, prompt+'. ')]
            def out_prompt_tokens(self, *wtf):
                return [(Token.OutPrompt, prompt+'= ')]
            def rewrite_prompt_tokens(self, *wtf):
                return [(Token.Prompt, prompt+'- ')]
        ip.prompts=soloprompts(ip)
    except ImportError:
        ip.prompt_manager.templates.update({
            'in':  'In [{color.number}{count}{color.prompt}] '+prompt+'> ',
            'in2':                              '   .{dots}. '+prompt+'. ',
            'out': 'Out[{color.number}{count}{color.prompt}] '+prompt+'> ',
        })
    except NameError:
        pass
    except KeyError:
        pass

set_prompt("SOLOPATH")

def load(module):
    """Use this function to import a module correctly given its path or its full name
    Allowed syntax: 
    load("hetept/data.py") 
    load("solo.hetept.data")"""
    if module.endswith(".py") or module.endswith(".pyc"):
        module_path = os.path.abspath(os.path.split(module)[0])
        module_name = os.path.splitext(os.path.split(module)[1])[0]
        if module_path.startswith(_path):
            module_name = module_path[len(_path)+1:].replace(os.path.sep, '.') + '.' + module_name
        else:
            raise ValueError("Module '%s' (at %s) not part of package." % (module_name,module_path))
    elif module.replace("_","").replace(".","").isalnum():
        # support package.sub_package.module syntax as well
        module_name = module
    else:
        raise ValueError("Cannot load module '%s'." % module)
    from importlib import import_module
    parent, scope = "", globals()
    for m in module_name.split('.'):
        module = import_module(parent + m)
        scope[m] = module
        parent += m + '.'
        scope = module.__dict__
    return module

def run(module, *argv):
    """Use this function to execute a python module directly, i.e.
    import it correctly and then execute its main(argv) function if it has one
    This is meant for testing purposes etc
    Allowed syntax: 
    run("hetept/data.py","-e", "FAR", "-p") 
    run("solo.hetept.data","-e", "FAR", "-p")"""
    module = load(module)
    if hasattr(module, "main"):
        if module.main.__code__.co_varnames and module.main.__code__.co_varnames[0]=="argv":
            return module.main([module.__name__] + list(argv))
        else:
            return module.main()

def main(argv):
    argv[0:1] = []
    if argv:
        return run(argv[0], *argv[1:])

if __name__=="__main__":
    main(sys.argv)