/*
 * get.c: Get 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 "get.h"
#include "get_helper.h"

typedef int (resp_cb_t)(char *name, char *value, char *type, void *ctx);

static int resp_cb(char *name, char *value, char *type, void *ctx)
{
	int ret;
	hal_param_t param_response;
	json_object *jreply = ctx;

	strncpyt(param_response.name, name, sizeof(param_response.name));

	param_response.type = get_eparam_type(type, &ret);
	if (ret) {
		ERR("Unsupported parameter type %s for %s", type, name);
		return -1;
	}

	/* json rpc expects true/false value for boolean */
	if (param_response.type == PARAM_BOOLEAN) {
		if (strncmp(value, "1", 2) == 0) {
			strncpyt(param_response.value, "true", sizeof(param_response.value));
		} else if (strncmp(value, "0", 2) == 0) {
			strncpyt(param_response.value, "false", sizeof(param_response.value));
		} else {
			strncpyt(param_response.value, value, sizeof(param_response.value));
		}
	} else {
		strncpyt(param_response.value, value, sizeof(param_response.value));
	}

	if (json_hal_add_param(jreply, GET_RESPONSE_MESSAGE, &param_response) != RETURN_OK) {
		ERR("Failed to add response for %s", name);
		return -1;
	}

	return 0;
}

static int get_value(hal_param_t *params, resp_cb_t resp_cb, void *ctx)
{
	struct dmctx bbf_ctx;
	struct dm_parameter *n = NULL;
	int ret = -1;

	memset(&bbf_ctx, 0, sizeof(bbf_ctx));
	bbf_init(&bbf_ctx);
	bbf_ctx.in_param = params->name;

	INFO("Get parameter: %s", params->name);

	if ((ret = bbfdm_cmd_exec(&bbf_ctx, BBF_GET_VALUE))) {
		ERR("Failed to get value for %s", params->name);
		goto Exit;
	}

	list_for_each_entry(n, &bbf_ctx.list_parameter, list) {
		if (resp_cb(n->name, n->data, n->type, ctx)) {
			goto Exit;
		}
	}

	ret = 0;
Exit:
	bbf_cleanup(&bbf_ctx);
	return ret;
}

int bbfdm_get_value(const json_object *jmsg, int param_count,
	json_object *jreply)
{
	int i;
	hal_param_t param_request;

	if (jmsg == NULL || jreply == NULL) {
		ERR("invalid parameter");
		return RETURN_ERR;
	}

	for (i = 0; i < param_count; i++) {
		/* Unpack the JSON and populate the data into request_param object */
		if (json_hal_get_param((json_object *)jmsg, i, GET_REQUEST_MESSAGE,
			&param_request) != RETURN_OK) {
			ERR("Failed to get parameter from json");
			return RETURN_ERR;
		}

		if (get_value(&param_request, resp_cb, jreply)) {
			ERR("Failed to get parameter value for %s", param_request.name);
			return RETURN_ERR;
		}
	}

	return RETURN_OK;
}
