# -*- coding: utf-8 -*-
"""The importhandler module of dolfin"""

# NOTE: The automatic documentation system in DOLFIN requires to _not_ define
# NOTE: classes or functions within this file. Use separate modules for that
# NOTE: purpose.

# System imports
from __future__ import print_function
import sys

# Import NumPy so it will not be screwed by imports after RTLD_GLOBAL is set
# Work around for lp:1085986
import numpy

# Work around lp:956939 and lp:961946
import io

# Store dl open flags to restore them after import
stored_dlopen_flags = sys.getdlopenflags()

# A try to get rid of problems with dynamic_cast of types defined in different
# SWIG modules. The problem rises from the dynamic loader not making all types
# available for all shared modules. The key is the RTLD_GLOBAL. RTLD_NOW is set
# by default. This seems to be similar to the dynamicloadmpi problem above.
# See: for references: http://gcc.gnu.org/faq.html#dso
if "linux" in sys.platform:
    # FIXME: What with other platforms?
    try:
        from ctypes import RTLD_NOW, RTLD_GLOBAL
    except ImportError:
        RTLD_NOW = 2
        RTLD_GLOBAL = 256
    sys.setdlopenflags(RTLD_NOW | RTLD_GLOBAL)

# Check for runtime dependencies
runtime_dependencies = ["ufl", "ffc", "ply.lex"]

for dep in runtime_dependencies:
    try:
        __import__(dep)
    except ImportError as e:
        import sys
        message = ["DOLFIN runtime dependency is not met.",
                   "Install the following python module: '%s' "  % dep,
                   "and make sure its location is listed in PYTHONPATH."]
        wrap = "-"*len(max(message, key=len))
        print()
        print(wrap)
        for s in message:
            print(s)
        print(wrap)
        print()
        sys.exit(1)
