/**
 * @file    chart.c
 * @brief   Feeding a CHART with samples.
 *          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 chart.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 CHART ([w.1] in chart.nxlay). */
#define WID_SIGNAL 1

/**
 * @brief  Replaces the samples (0..65535 each, at most 256).
 * @param[in] samples Array of count values; NULL clears the chart.
 * @param[in] count   Number of samples; more than 256 refuses the whole batch.
 * @return ERR_OK, ERR_NOT_FOUND, or ERR_FULL.
 * @note   NX_WP_SERIES is a BLOB: an NxSeriesHead (format, count) followed by
 *         the samples as 16-bit little-endian values, written byte by byte so
 *         it does not depend on the host's byte order. Samples are state and do
 *         not rebuild the panel. The bars are scaled by the declared
 *         num_min..num_max.
 */
NxLong chart_feed(NxPluginCtx ctx, const NxWord *samples, NxWord count)
{
    unsigned char buf[4 + 2 * NX_WSERIES_MAX_SAMPLES];
    NxPropVal     v;
    NxWord        i;

    if (samples == (const NxWord *)0)
    {
        count = 0;
    }
    if (count > NX_WSERIES_MAX_SAMPLES)
    {
        return ERR_FULL;
    }
    buf[0] = (unsigned char)NX_WSERIES_FMT_U16;
    buf[1] = 0;
    buf[2] = (unsigned char)(count & 0xFF);
    buf[3] = (unsigned char)((count >> 8) & 0xFF);
    for (i = 0; i < count; i++)
    {
        buf[4 + 2 * i]     = (unsigned char)(samples[i] & 0xFF);
        buf[4 + 2 * i + 1] = (unsigned char)((samples[i] >> 8) & 0xFF);
    }
    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   = (count == 0) ? 0 : (NxDword)(4 + 2 * count);   /* zero length = no samples */
    return s_host->SetWidgetProp(ctx, 0, WID_SIGNAL, NX_WP_SERIES, &v);
}
