/* setup.c */

#include "stats.h"


static char *root = NULL;
static char *ranges = NULL;

#define  defroot       "$"
#define  defranges     "1024, 10240, 102400, 1048576"

#define  choices_file  "<stats$dir>.Choices"



static void read_defaults (void)
{
    FILE *f = fopen (choices_file, "r");
    int n;

    /* set default defaults just in case */
    strcpy (root, defroot);
    strcpy (ranges, defranges);

    if (f == NULL)
    {
        error_box (error_lookup ("CantRead"));
        return;
    }

    fgets (root, 256, f);
    fgets (ranges, 256, f);

    /* remove any terminating newline */
    n = strlen (root);
    if (root[n] == '\n')
        root[n] = 0;
    n = strlen (ranges);
    if (ranges[n] == '\n')
        ranges[n] = 0;

    fclose (f);

    return;
}


static void write_defaults (void)
{
    FILE *f = fopen (choices_file, "w");

    if (f == NULL)
    {
        error_box (error_lookup ("CantWrite"));
        return;
    }

    fprintf (f, "%s\n%s\n", root, ranges);
    fclose (f);

    return;
}


static void put_values (ObjectId window)
{
    writablefield_set_value (0, window, ID_Setup_Root, root);
    writablefield_set_value (0, window, ID_Setup_Ranges, ranges);

    return;
}


static void get_values (ObjectId window)
{
    writablefield_get_value (0, window, ID_Setup_Root, root, 256, NULL);
    writablefield_get_value (0, window, ID_Setup_Ranges, ranges, 256, NULL);

    return;
}


Bool setup_abouttobeshown
(
    int code,
    ToolboxEvent *event,
    IdBlock *idblock,
    void *handle
)
{
    IGNORE (code);
    IGNORE (event);
    IGNORE (handle);

    /* read default values from file if this is the first time */
    if (root == NULL)
    {
        root = malloc (256);
        ranges = malloc (256);
        if (ranges == NULL)
            error_exit ( error_lookup ("NoMem") );

        read_defaults ();
    }

    /* fill in dbox fields */
    put_values (idblock->self_id);

    return TRUE;
}


Bool setup_default
(
    int code,
    ToolboxEvent *event,
    IdBlock *idblock,
    void *handle
)
{
    IGNORE (code);
    IGNORE (event);
    IGNORE (handle);

    read_defaults ();
    put_values (idblock->self_id);

    return TRUE;
}


Bool setup_save
(
    int code,
    ToolboxEvent *event,
    IdBlock *idblock,
    void *handle
)
{
    IGNORE (code);
    IGNORE (event);
    IGNORE (handle);

    get_values (idblock->self_id);
    write_defaults ();

    return TRUE;
}


Bool setup_cancel
(
    int code,
    ToolboxEvent *event,
    IdBlock *idblock,
    void *handle
)
{
    IGNORE (code);
    IGNORE (handle);

    if ((event->hdr.flags & ActionButton_Selected_Adjust) != 0)
        put_values (idblock->self_id);

    return TRUE;
}


Bool setup_go
(
    int code,
    ToolboxEvent *event,
    IdBlock *idblock,
    void *handle
)
{
    IGNORE (code);
    IGNORE (event);
    IGNORE (handle);

    get_values (idblock->self_id);
    scan_start (root, ranges);

    return TRUE;
}
