import logging
import sys

import spyder_kernels.console.start as spyder_start

from .kernelapp import PyXLLSpyderKernelApp

_log = logging.getLogger(__name__)


if not hasattr(sys, "_spyder_app"):
    sys._spyder_app = None


def start_kernel():
    """Starts the ipython kernel and returns the kernel app object."""
    _log.debug("Starting Spyder kernel...")

    if sys._spyder_app and sys._spyder_app.is_running:
        _log.info("Spyder already running")
        return sys._spyder_app

    # Patch spyder_start.SpyderKernelApp to use our own class
    spyder_start.SpyderKernelApp = PyXLLSpyderKernelApp

    # Start the app if needed
    if not PyXLLSpyderKernelApp.initialized():
        spyder_start.main()

    # Keep a reference to the kernel even if this module is reloaded
    ipy = sys._spyder_app = PyXLLSpyderKernelApp.instance()

    # The kernel should be started already, but start it again if it's not
    if not ipy.is_running:
        ipy.start()

    # patch user_global_ns so that it always references the user_ns dict
    setattr(ipy.shell.__class__, "user_global_ns", property(lambda self: self.user_ns))

    # Use the inline matplotlib backend
    mpl = ipy.shell.find_magic("matplotlib")
    if mpl:
        try:
            mpl("inline")
        except ImportError:
            pass

    _log.info("Spyder kernel started")
    return sys._spyder_app
