"""
The functions in this module are the implemenations of the functions exposed
to Excel in the pyxll module.

They are separated into this module to minimize the time taken to import the
pyxll module, as that is done when starting Excel.
"""

import ctypes
import logging

import win32clipboard

from ..kernel import start_kernel

_log = logging.getLogger(__name__)


def start_spyder_kernel_ribbon_action():
    """Start the Spyder kernel and display the connection file.
    This is used by the ribbon callback.
    """
    try:
        # Start the kernel
        app = start_kernel()
        _log.info(
            f"Spyder connection file: {app.connection_dir}\\{app.connection_file}"
        )

        # Copy the connection file to the clipboard so the user can paste it into Spyder
        win32clipboard.OpenClipboard()
        try:
            win32clipboard.EmptyClipboard()
            win32clipboard.SetClipboardText(app.connection_file)
        finally:
            win32clipboard.CloseClipboard()

        # Alert the user
        ctypes.windll.user32.MessageBoxW(
            None,
            (
                "The Spyder kernel is running and you can now connect\n"
                "Spyder using the following connection file:\n\n"
                f"{app.connection_file}\n\n"
                "The connection file name has been copied to the clipboard."
            ),
            "Spyder kernel running",
            0x40,  # MB_ICONASTERISK | MB_OK
        )

        return True
    except Exception as e:
        ctypes.windll.user32.MessageBoxW(
            None,
            f"An error occurred when trying to start the Spyder kernel:\n\n{e}",
            "Error starting Spyder kernel",
            0x10,  # MB_ICONERROR | MB_OK
        )
        raise


def start_spyder_kernel_macro():
    """Start the Spyder kernel and return the name of the connection file.
    This is used by the macro to start the kernel.
    """
    app = start_kernel()
    _log.info(f"Spyder connection file: {app.connection_dir}\\{app.connection_file}")
    return app.connection_file
