/**
 * @file    filepick.c
 * @brief   Reading the path a user picked in a FILEPICK.
 *          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 filepick.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 FILEPICK ([w.1] in filepick.nxlay). */
#define WID_FIRMWARE 1

/**
 * @brief  Reads the currently chosen path.
 * @param[in]  ctx  This mount's context.
 * @param[out] path Receives the path (empty string when nothing was chosen).
 * @param[in]  cap  Capacity of path; 264 bytes always fit (the path is at most 263 bytes plus the NUL).
 * @return ERR_OK; ERR_BUFFER_TOO_SMALL; ERR_NOT_FOUND when the widget does not exist.
 * @note   The path is the VALUE of the widget (a string). Picking a file also
 *         sends NX_WEVT_CHANGED, but reading it on demand, for example in the
 *         handler of a "Start" button, is just as good.
 */
NxLong filepick_path(NxPluginCtx ctx, char *path, NxDword cap)
{
    NxPropVal out;
    NxDword   needed = 0;

    memset(&out, 0, sizeof(out));
    out.SizeOfStruct = (NxDword)sizeof(out);
    return s_host->GetWidgetProp(ctx, 0, WID_FIRMWARE, NX_WP_VALUE, &out, path, cap, &needed);
}

/**
 * @brief  Presets the path shown in the box (e.g. the last used file).
 */
NxLong filepick_preset(NxPluginCtx ctx, const char *path)
{
    NxPropVal v;

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