"""Button and menu callbacks of the Deadline Cloud scheduler node."""

import functools


def callback(kwargs):
    """Submit and the Farm and Queue menus are the scheduler's own. Every other button is the ROP's."""
    from deadline.houdini_pdg.houdini.host import (
        farm_and_queue_menus,
        move_queue_folders_above_submit,
        submit,
    )

    name = kwargs["parm"].name()
    if name == "submit":
        submit(kwargs["node"])
        return
    if name in ("farm", "queue"):
        update = functools.partial(update_queue_parameters_callback, kwargs)
        farm_and_queue_menus.save_pick(kwargs["node"], name, update)
        return
    from deadline_cloud_for_houdini.submitter import callback as rop_callback

    # Settings and Update Queue Parameters add the queue folders after Submit, and write the
    # farm and queue names into the menus, which hold IDs, so the names are kept and the IDs
    # go back. Either may change the login.
    try:
        rop_callback(kwargs)
        move_queue_folders_above_submit(kwargs["node"])
    finally:
        farm_and_queue_menus.show_saved_ids(kwargs["node"])
        farm_and_queue_menus.load_lists(reload=True)


def update_queue_parameters_callback(kwargs):
    """Lay the node out as its definition does, then run the ROP's farm, queue and queue parameter update."""
    from deadline.houdini_pdg.houdini.host import (
        farm_and_queue_menus,
        move_queue_folders_above_submit,
        rebuild_layout_from_definition,
    )
    from deadline_cloud_for_houdini.submitter import update_queue_parameters_callback as rop

    # The lists load in the background. The layout needs no login, so a failed one still leaves
    # the right tabs. The queue folders then move back above Submit, and the names the ROP
    # wrote are kept as the IDs always go back.
    farm_and_queue_menus.load_lists()
    rebuild_layout_from_definition(kwargs["node"])
    try:
        rop(kwargs)
        move_queue_folders_above_submit(kwargs["node"])
    finally:
        farm_and_queue_menus.show_saved_ids(kwargs["node"])
