"""
Entry points for PyXLL integration.

These are picked up automatically when PyXLL starts to add Spyder
functionality to Excel as long as this package is installed.

This module is kept intentionally light and all the actual functions
are implemented in the impl module. This is to minimize import time
to avoid slowing down Excel when opening.

To install this package use::

    pip install pyxll_jupyter

"""

import logging
import sys

from pyxll import get_config, xl_macro

_log = logging.getLogger(__name__)


if sys.version_info[:2] >= (3, 7):
    import importlib.resources

    def _resource_bytes(package, resource_name):
        return importlib.resources.read_binary(package, resource_name)

else:
    import pkg_resources

    def _resource_bytes(package, resource_name):
        return pkg_resources.resource_stream(package, resource_name).read()


def start_spyder_kernel(*args):
    """Ribbon handler for starting the Spyder kernel."""
    from .impl import start_spyder_kernel_ribbon_action

    return start_spyder_kernel_ribbon_action()


@xl_macro(name="StartSpyderKernel")
def start_spyder_kernel_macro():
    """
    Excel macro for starting the kernel.
    Returns the connection file name.
    """
    from .impl import start_spyder_kernel_macro

    return start_spyder_kernel_macro()


def modules():
    """Entry point for getting the pyxll modules.
    Returns a list of module names."""
    return [__name__]


def ribbon():
    """Entry point for getting the pyxll ribbon file.
    Returns a list of (filename, data) tuples.
    """
    cfg = get_config()

    disable_ribbon = False
    if cfg.has_option("SPYDER", "disable_ribbon"):
        try:
            disable_ribbon = bool(int(cfg.get("SPYDER", "disable_ribbon")))
        except (ValueError, TypeError):
            _log.error("Unexpected value for SPYDER.disable_ribbon.")

    if disable_ribbon:
        return []

    ribbon = _resource_bytes("pyxll_spyder.resources", "ribbon.xml").decode("utf-8")
    return [(None, ribbon)]
