/*
 * set.c: Set handler for bbfdmd
 *
 * Copyright (C) 2023 IOPSYS Software Solutions AB. All rights reserved.
 *
 * Author: Iryna Antsyferova <iryna.antsyferova@iopsys.eu>
 *
 * See LICENSE file for license related information.
 */

#include "set.h"
#include "add_delete.h"
#include "get_helper.h"
#include "service_helper.h"

int bbfdm_set_value(const json_object *jmsg, int param_count,
	json_object *jreply)
{
	int i;
	int fault;
	int changed = 0;
	hal_param_t param;
	struct dmctx bbf_ctx;

	if (jmsg == NULL || jreply == NULL) {
		ERR("setParameters cb: invalid memory");
		return RETURN_ERR;
	}

	for (i = 0; i < param_count; i++) {
		/* Unpack the JSON and polulate the data into request_param object */
		if (json_hal_get_param((json_object *)jmsg, i, SET_REQUEST_MESSAGE,
			&param) != RETURN_OK) {
			ERR("setParameters cb: failed get parameter");
			return RETURN_ERR;
		}

		INFO("Set parameter: %s=%s", param.name, param.value);

		memset(&bbf_ctx, 0, sizeof(bbf_ctx));
		bbf_init(&bbf_ctx);
		bbf_ctx.in_param = param.name;
		bbf_ctx.in_value = param.value;

		fault = bbfdm_cmd_exec(&bbf_ctx, BBF_SET_VALUE);
		/* Try to add a new object and try to set the value again */
		if (fault == FAULT_9005 && !bbfdm_add_object(&bbf_ctx))
			fault = bbfdm_cmd_exec(&bbf_ctx, BBF_SET_VALUE);
		if (fault)
			ERR("setParameters cb: failed setting (%s) (%s)", param.name, param.value);
		else
			changed = 1;

		bbf_cleanup(&bbf_ctx);

		INFO("Result: %s", !fault ? "ok" : "error");

		/* Pack the json response and reply back. */
		if (json_hal_add_result_status(jreply, fault == 0 ? RESULT_SUCCESS :
			RESULT_FAILURE) != RETURN_OK) {
			ERR("setParameters cb: failed setting status");
			return RETURN_ERR;
		}
	}

	if (changed)
		restart_services();

	return RETURN_OK;
}

