#!python
import os, re
from distutils.version import LooseVersion
from yt.mods import *
from yt.data_objects.data_containers import YTDataContainer
namespace = locals().copy()
namespace.pop("__builtins__", None)

doc = """\

==================
| Welcome to yt! |
==================

"""

try:
    import IPython
except:
    print 'ipython is not available. using default python interpreter.'
    import code
    import sys
    code.interact(doc, None, namespace)
    sys.exit()

if LooseVersion(IPython.__version__) <= LooseVersion('0.10'):
    api_version = '0.10'
elif LooseVersion(IPython.__version__) <= LooseVersion('1.0'):
    api_version = '0.11'
else:
    api_version = '1.0'

if api_version == "0.10" and "DISPLAY" in os.environ:
    from matplotlib import rcParams
    ipbackends = dict(Qt4 = IPython.Shell.IPShellMatplotlibQt4,
                      WX  = IPython.Shell.IPShellMatplotlibWX,
                      GTK = IPython.Shell.IPShellMatplotlibGTK,
                      Qt  = IPython.Shell.IPShellMatplotlibQt)
    bend = (rcParams["backend"]).rstrip('Agg')

    try:
        ip_shell = ipbackends[bend](user_ns=namespace)
    except KeyError:
        ip_shell = IPython.Shell.IPShellMatplotlib(user_ns=namespace)
elif api_version == "0.10":
    ip_shell = IPython.Shell.IPShellMatplotlib(user_ns=namespace)
else:
    if api_version == "0.11":
        from IPython.frontend.terminal.interactiveshell import \
            TerminalInteractiveShell
    elif api_version == "1.0":
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
    else:
        raise RuntimeError
    ip_shell = TerminalInteractiveShell(user_ns=namespace, banner1 = doc,
                    display_banner = True)
    if "DISPLAY" in os.environ: ip_shell.enable_pylab(import_all=False)


# The rest is a modified version of the IPython default profile code

""" User configuration file for IPython

This is a more flexible and safe way to configure ipython than *rc files
(ipythonrc, ipythonrc-pysh etc.)

This file is always imported on ipython startup. You can import the
ipython extensions you need here (see IPython/Extensions directory).

Feel free to edit this file to customize your ipython experience.

Note that as such this file does nothing, for backwards compatibility.
Consult e.g. file 'ipy_profile_sh.py' for an example of the things 
you can do here.

See http://ipython.scipy.org/moin/IpythonExtensionApi for detailed
description on what you could do here.
"""

# Most of your config files and extensions will probably start with this import

#import IPython.ipapi
if api_version == "0.10":
    ip = ip_shell.IP.getapi()
    try_next = IPython.ipapi.TryNext
    kwargs = dict(sys_exit=1, banner=doc)
elif api_version in ("0.11", "1.0"):
    ip = ip_shell
    try_next = IPython.core.error.TryNext
    kwargs = dict()

ip.ex("from yt.mods import *")
ip.ex("import yt")

# Now we add some tab completers, in the vein of:
# http://pymel.googlecode.com/svn/trunk/tools/ipymel.py
# We'll start with some fields.

import re
def yt_fieldname_completer(self, event):
    """Match dictionary completions"""
    #print "python_matches", event.symbol
    #text = event.symbol # Not sure why this no longer works
    text = event.line
    #print repr(text)
    # Another option, seems to work great. Catches things like ''.<tab>
    #print repr(text), dir(text)
    #m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
    m = re.match(r"(\S+(\.\w+)*)\[[\'\\\"](\w*)$", text)

    if not m:
        raise try_next
    
    expr, attr = m.group(1, 3)
    #print "COMPLETING ON ", expr, attr
    #print type(self.Completer), dir(self.Completer)
    #print self.Completer.namespace
    #print self.Completer.global_namespace
    try:
        obj = eval(expr, self.Completer.namespace)
    except:
        try:
            obj = eval(expr, self.Completer.global_namespace)
        except:
            raise IPython.ipapi.TryNext 
        
    if isinstance(obj, (YTDataContainer, ) ):
        #print "COMPLETING ON THIS THING"
        all_fields = [f for f in sorted(
                obj.ds.field_list + obj.ds.derived_field_list)]
        #matches = self.Completer.python_matches(text)
        #print "RETURNING ", all_fields
        return all_fields


    raise try_next

ip.set_hook('complete_command', yt_fieldname_completer , re_key = ".*" )

ip_shell.mainloop(**kwargs)
