/**
 * @file    checkbox.c
 * @brief   Reacting to a CHECKBOX and setting it from code.
 *          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 checkbox.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 CHECKBOX ([w.1] in checkbox.nxlay). */
#define WID_ENABLE 1

/**
 * @brief  Widget event handler.
 * @note   I2C Worker Thread, so ExecSync() is allowed here.
 */
void NX_CALL checkbox_on_event(NxPluginCtx ctx, NxByte panel_id, NxWord widget_id,
                       const NxWidgetEvent *evt)
{
    NX_UNUSED_ARG(panel_id);
    if (widget_id == WID_ENABLE && evt->kind == NX_WEVT_CHANGED &&
        evt->val.kind == NX_WKIND_I64)
    {
        s_host->LogWrite(ctx, NX_LOG_INFO,
                         (evt->val.u.i64 != 0) ? "checkbox: on" : "checkbox: off");
    }
}

/**
 * @brief  Ticks or clears the box.
 * @param[in] on Non-zero = checked.
 */
NxLong checkbox_set(NxPluginCtx ctx, int on)
{
    NxPropVal v;

    memset(&v, 0, sizeof(v));
    v.SizeOfStruct = (NxDword)sizeof(v);
    v.kind         = (NxWord)NX_WKIND_I64;
    v.u.i64        = (on != 0) ? 1 : 0;
    return s_host->SetWidgetProp(ctx, 0, WID_ENABLE, NX_WP_VALUE, &v);
}
