#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <pslib.h>

#include "pmConfigMask.h"

psMaskType pmConfigMask(const char *masks, const pmConfig *config)
{
    assert (config);
    PS_ASSERT_STRING_NON_EMPTY(masks, 0);

    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, "MASKS"); // The recipe
    if (!recipe) {
        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find MASKS recipe.");
        return 0;
    }

    psMaskType mask = 0;                // Mask value, to return

    psArray *names = psStringSplitArray(masks, " ,;", false); // Array of symbolic names
    for (int i = 0; i < names->n; i++) {
        const char *name = names->data[i]; // Symbolic name of interest
        bool mdok;                      // Status of MD lookup
        psMaskType value = psMetadataLookupU8(&mdok, recipe, name);
        if (!mdok) {
            psError(PS_ERR_BAD_PARAMETER_VALUE, false,
                    "Unable to find mask value for %s in MASK recipe", name);
            psFree(names);
            return 0;
        }
        mask |= value;
    }
    psFree(names);

    return mask;
}
