/**
 * @file    textbox.c
 * @brief   Reading what the user typed into a TEXTBOX, and writing the box.
 *          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 textbox.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 TEXTBOX ([w.1] in textbox.nxlay). */
#define WID_NAME 1

/** @brief The last committed text (copied: evt->val.u.str.ptr is only valid during the call). */
static char s_name[128] = "";

/**
 * @brief  Widget event handler.
 * @note   I2C Worker Thread. CHANGED arrives when the user commits the text
 *         (Enter, or moving focus away), not on every keystroke.
 */
void NX_CALL textbox_on_event(NxPluginCtx ctx, NxByte panel_id, NxWord widget_id,
                      const NxWidgetEvent *evt)
{
    size_t n;

    NX_UNUSED_ARG(ctx);
    NX_UNUSED_ARG(panel_id);
    if (widget_id == WID_NAME && evt->kind == NX_WEVT_CHANGED &&
        evt->val.kind == NX_WKIND_STR && evt->val.u.str.ptr != (const char *)0)
    {
        n = evt->val.u.str.len;
        if (n > sizeof(s_name) - 1)
        {
            /* A TEXTBOX value can be far longer (32767 code points); this demo
             * keeps 127 bytes and may cut a multi-byte character. */
            n = sizeof(s_name) - 1;
        }
        memcpy(s_name, evt->val.u.str.ptr, n);
        s_name[n] = '\0';
    }
}

/**
 * @brief  Replaces the text in the box (e.g. after loading a saved setting).
 * @return ERR_OK or an error code. Does not trigger textbox_on_event().
 */
NxLong textbox_set(NxPluginCtx ctx, const char *text)
{
    NxPropVal v;

    memset(&v, 0, sizeof(v));
    v.SizeOfStruct = (NxDword)sizeof(v);
    v.kind         = (NxWord)NX_WKIND_STR;
    v.u.str.ptr    = text;
    v.u.str.len    = (NxDword)strlen(text);
    return s_host->SetWidgetProp(ctx, 0, WID_NAME, NX_WP_VALUE, &v);
}
