#!python
from __future__ import print_function
import os
import re
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 ImportError:
    print('ipython is not available. using default python interpreter.')
    import code
    import sys
    code.interact(doc, None, namespace)
    sys.exit()

from IPython.terminal.interactiveshell import TerminalInteractiveShell
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
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.


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)
