#! /usr/bin/env python
import sys, os, getopt

MOBYLEHOME = None
if os.environ.has_key('MOBYLEHOME'):
    MOBYLEHOME = os.environ['MOBYLEHOME']
if not MOBYLEHOME:
    sys.exit('MOBYLEHOME must be defined in your environment')

if ( MOBYLEHOME ) not in sys.path:
    sys.path.append( MOBYLEHOME )
if ( os.path.join( MOBYLEHOME , 'Src' ) ) not in sys.path:    
    sys.path.append( os.path.join( MOBYLEHOME , 'Src' ) )

from Mobyle.ConfigManager import Config
_cfg = Config()

class Console(object):
    # shamelessly stolen from https://code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py!

    shells = ['ipython','bpython','python']

    def __init__(self,locals={}):
        self.locals = locals
        
    def ipython(self):
        try:
            from IPython import embed
            embed(user_ns=self.locals)
        except ImportError:
            # IPython < 0.11
            # Explicitly pass an empty list as arguments, because otherwise
            # IPython would use sys.argv from this script.
            try:
                from IPython.Shell import IPShell
                shell = IPShell(argv=[])
                shell.mainloop()
            except ImportError:
                # IPython not found at all, raise ImportError
                raise
    
    def bpython(self):
        import bpython
        bpython.embed(locals_=self.locals)
    
    def run_shell(self, shells=[]):
        for shell in shells or self.shells:
            try:
                return getattr(self, shell)()
            except ImportError:
                pass
        raise ImportError
    
    def python(self):
        import code
        imported_objects = {}
        try: # Try activating rlcompleter, because it's handy.
            import readline
        except ImportError:
            pass
        else:
            # We don't have to wrap the following import in a 'try', because
            # we already know 'readline' was imported successfully.
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(imported_objects).complete)
            readline.parse_and_bind("tab:complete")
        code.interact(local=self.locals)

if __name__ == '__main__':

    def usage():
        print """
        Usage: mobshell [OPTION]... FILE... 
        Run mobyle shell
    
        option:
            -i or --ipython    force ipython usage
            -b or --bpython    force ipython usage
            -p or --python    force "simple" python usage
            -h or --help  ... Print this message and exit.
        """

    c = Console(locals())

    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hibp", ["help", "ipython", "bpython", "python"] )
    except getopt.GetoptError:
        usage()
        sys.exit( 1 )

    shells = []
    for option , value in opts:     
        if option in ( "-h", "--help" ):
            usage()
            sys.exit( 0 )
        if option in ( "-i", "--ipython"):
            shells.append("ipython")
        if option in ( "-b", "--bpython"):
            shells.append("bpython")
        if option in ( "-p", "--python"):
            shells.append("python")

    c.run_shell(shells)