# Copyright 2012 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

"""Provides a custom PEP-302 import hook to load GI libraries"""

import sys
import warnings
import importlib
from contextlib import contextmanager

from .clib.gir import GIRepository
from . import const, overrides
from .util import PyGIWarning
from .module import get_introspection_module

_versions = {}


def require_version(namespace, version):
    """Set a version for the namespace to be loaded.
    This needs to be called before importing the namespace or any
    namespace that depends on it.
    """

    global _versions

    repo = GIRepository()
    namespaces = repo.get_loaded_namespaces()

    if namespace in namespaces:
        loaded_version = repo.get_version(namespace)
        if loaded_version != version:
            raise ValueError('Namespace %s is already loaded with version %s' %
                             (namespace, loaded_version))

    if namespace in _versions and _versions[namespace] != version:
        raise ValueError('Namespace %s already requires version %s' %
                         (namespace, _versions[namespace]))

    available_versions = repo.enumerate_versions(namespace)
    if not available_versions:
        raise ValueError('Namespace %s not available' % namespace)

    if version not in available_versions:
        raise ValueError('Namespace %s not available for version %s' %
                         (namespace, version))

    _versions[namespace] = version


def get_required_version(namespace):
    """Returns the version string for the namespace that was previously
    required through 'require_version' or None
    """

    global _versions

    return _versions.get(namespace, None)


def extract_namespace(fullname):
    for prefix in const.PREFIX:
        if fullname.startswith(prefix):
            namespace = fullname[len(prefix) + 1:]
            if "." not in namespace:
                return namespace


def install_import_hook():
    sys.meta_path.append(Importer())


@contextmanager
def _check_require_version(namespace, stacklevel):
    """A context manager which tries to give helpful warnings
    about missing gi.require_version() which could potentially
    break code if only an older version than expected is installed
    or a new version gets introduced.

    ::

        with _check_require_version("Gtk", stacklevel):
            load_namespace_and_overrides()
    """

    repository = GIRepository()
    was_loaded = repository.is_registered(namespace)

    yield

    if was_loaded:
        # it was loaded before by another import which depended on this
        # namespace or by C code like libpeas
        return

    if namespace in ("GLib", "GObject", "Gio"):
        # part of glib (we have bigger problems if versions change there)
        return

    if get_required_version(namespace) is not None:
        # the version was forced using require_version()
        return

    version = repository.get_version(namespace)
    warnings.warn(
        "%(namespace)s was imported without specifying a version first. "
        "Use gi.require_version('%(namespace)s', '%(version)s') before "
        "import to ensure that the right version gets loaded."
        % {"namespace": namespace, "version": version},
        PyGIWarning, stacklevel=stacklevel)


def get_import_stacklevel(import_hook):
    """Returns the stacklevel value for warnings.warn() for when the warning
    gets emitted by an imported module, but the warning should point at the
    code doing the import.

    Pass import_hook=True if the warning gets generated by an import hook
    (warn() gets called in load_module(), see PEP302)
    """

    py_version = sys.version_info[:2]
    if py_version <= (3, 2):
        # 2.7 included
        return 4 if import_hook else 2
    elif py_version == (3, 3):
        return 8 if import_hook else 10
    elif py_version == (3, 4):
        return 10 if import_hook else 8
    else:
        # fixed again in 3.5+, see https://bugs.python.org/issue24305
        return 4 if import_hook else 2


class Importer(object):
    """Import hook according to http://www.python.org/dev/peps/pep-0302/"""

    def find_module(self, fullname, path=None):
        namespace = extract_namespace(fullname)

        if not namespace:
            return

        repository = GIRepository()

        # is_registered() is faster than enumerate_versions() and
        # in the common case of a namespace getting loaded before its
        # dependencies, is_registered() returns True for all dependencies.
        if repository.is_registered(namespace) or \
                repository.enumerate_versions(namespace):
            return self
        else:
            raise ImportError('cannot import name %s, '
                              'introspection typelib not found' % namespace)

    def load_module(self, fullname):
        global _versions

        # Dependency already loaded, skip
        if fullname in sys.modules:
            return sys.modules[fullname]

        namespace = extract_namespace(fullname)
        repository = GIRepository()

        stacklevel = get_import_stacklevel(import_hook=True)
        with _check_require_version(namespace, stacklevel=stacklevel):
            introspection_module = get_introspection_module(namespace)

            # Import all dependencies first so their init functions
            # (gdk_init, ..) in overrides get called.
            # https://bugzilla.gnome.org/show_bug.cgi?id=656314
            for dep in repository.get_immediate_dependencies(namespace):
                importlib.import_module(
                    const.PREFIX[0] + '.' + dep.split("-")[0])

            # Import a override module if available.
            proxy = overrides.load_overrides(introspection_module)

        proxy.__loader__ = self
        for prefix in const.PREFIX:
            module_key = prefix + "." + namespace
            sys.modules[module_key] = proxy

        return proxy
