/**
 * @file    spin.c
 * @brief   Reading a SPIN as a signed number and setting it.
 *          A reading aid for the tutorial page "widget-types", not a complete
 *          plugin: the functions below would be wired into an IcPlugin
 *          (on_widget_event) or called from init()/a Worker callback.
 *
 * @note    ASCII-only and C89 on purpose (VC6 / CP950 safe, and it must pass
 *          the syntax-only guard). The widget ids match spin.nxlay.
 */

#include <string.h>

#include "nexus_plugin_api.h"

/** @brief The HostAPI table, saved by init() (not shown here). */
static const NxHostApi *s_host = (const NxHostApi *)0;

/** @brief widget id of the SPIN ([w.1] in spin.nxlay). */
#define WID_GAIN 1

/** @brief The last value the user chose. */
static long s_gain = 0;

/**
 * @brief  Widget event handler.
 * @note  evt->val is an NX_WKIND_I64: a SPIN value is already signed, no cast
 *         needed (the range here is -10..10).
 */
void NX_CALL spin_on_event(NxPluginCtx ctx, NxByte panel_id, NxWord widget_id,
                   const NxWidgetEvent *evt)
{
    NX_UNUSED_ARG(ctx);
    NX_UNUSED_ARG(panel_id);
    if (widget_id == WID_GAIN && evt->kind == NX_WEVT_CHANGED &&
        evt->val.kind == NX_WKIND_I64)
    {
        s_gain = (long)evt->val.u.i64;
    }
}

/**
 * @brief  Sets the spin; the value is clamped to num_min..num_max.
 */
NxLong spin_set(NxPluginCtx ctx, long gain)
{
    NxPropVal v;

    memset(&v, 0, sizeof(v));
    v.SizeOfStruct = (NxDword)sizeof(v);
    v.kind         = (NxWord)NX_WKIND_I64;
    v.u.i64        = (NxI64)gain;
    return s_host->SetWidgetProp(ctx, 0, WID_GAIN, NX_WP_VALUE, &v);
}
