/**
 * @file    table.c
 * @brief   Filling a TABLE with rows.
 *          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 table.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 TABLE ([w.1] in table.nxlay). */
#define WID_REGS 1

/**
 * @brief  Appends one record of an NX_WP_ROWS blob: an NxRowHead, the name, the
 *         value, padded to a multiple of 4 bytes.
 * @return The offset just after the record.
 */
static NxDword add_row(unsigned char *buf, NxDword pos, const char *name,
                       const char *value, NxDword style)
{
    NxRowHead h;
    NxDword   rec;

    h.name_len  = (NxWord)strlen(name);
    h.value_len = (NxWord)strlen(value);
    h.style     = style;
    rec = ((NxDword)sizeof(h) + h.name_len + h.value_len + 3u) & ~3u;
    memset(buf + pos, 0, rec);
    memcpy(buf + pos, &h, sizeof(h));
    memcpy(buf + pos + sizeof(h), name, h.name_len);
    memcpy(buf + pos + sizeof(h) + h.name_len, value, h.value_len);
    return pos + rec;
}

/**
 * @brief  Replaces all rows of the list.
 * @return ERR_OK; ERR_FULL when the blob is over the capacity limit: the whole
 *         batch is refused, never truncated.
 * @note   Any thread. NX_WP_ROWS is a BLOB of row records (NxRowHead + name +
 *         value). Row data is state: it does not rebuild the panel, so calling
 *         this from a poll is fine. Scrolling belongs to the host.
 */
NxLong table_fill(NxPluginCtx ctx)
{
    unsigned char buf[2 * 32];
    NxPropVal     v;
    NxDword       pos;

    pos = add_row(buf, 0, "REG[00]", "0x1A", (NxDword)NX_COLOR_DEFAULT);
    pos = add_row(buf, pos, "REG[01]", "0xFF", (NxDword)NX_COLOR_WARN);
    memset(&v, 0, sizeof(v));
    v.SizeOfStruct = (NxDword)sizeof(v);
    v.kind         = (NxWord)NX_WKIND_BLOB;
    v.u.blob.ptr   = buf;
    v.u.blob.len   = pos;
    return s_host->SetWidgetProp(ctx, 0, WID_REGS, NX_WP_ROWS, &v);
}
