#!python
from __future__ import print_function

import os
import re

from IPython.terminal.interactiveshell import TerminalInteractiveShell

from yt.data_objects.data_containers import YTDataContainer
from yt.mods import *

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()

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

def yt_simple_fieldname_completer(self, event):
    """Match dictionary completions"""
    text = event.line
    # The regexp matches anything like foo.bar.baz['f
    m = re.match(r"(\S+(\.\w+)*)\[[\'\\\"](\w*)$", text)

    if not m:
        raise try_next

    expr, attr = m.group(1, 3)

    try:
        obj = eval(expr, self.Completer.namespace)
    except Exception:
        try:
            obj = eval(expr, self.Completer.global_namespace)
        except Exception:
            raise IPython.ipapi.TryNext

    if isinstance(obj, YTDataContainer):
        all_types = list(set(
            [ftype for ftype, _ in
             obj.ds.field_list + obj.ds.derived_field_list]))
        return all_types

    raise try_next

def yt_tuple_fieldname_completer(self, event):
    """Match dictionary completions"""
    text = event.line
    # The regexp matches anything like foo.bar.baz['toto', 'tata
    m = re.match(r"(\S+(\.\w+)*)\[[\'\\\"](\S+)[\'\\\"],\s*[\'\\\"](\S+)", text)

    if not m:
        raise try_next

    expr, prefix, attr = m.group(1, 3, 4)

    try:
        obj = eval(expr, self.Completer.namespace)
    except Exception:
        try:
            obj = eval(expr, self.Completer.global_namespace)
        except Exception:
            raise IPython.ipapi.TryNext

    if isinstance(obj, YTDataContainer):
        all_fields = [
            fname for ftype, fname in
            obj.ds.field_list + obj.ds.derived_field_list
            if prefix == ftype
        ]
        return all_fields


    raise try_next

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

ip_shell.mainloop(**kwargs)
