/*
 * add_delete.c: Add/Delete 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 "common.h"
#include "add_delete.h"
#include "get_helper.h"
#include "service_helper.h"

int bbfdm_add_object(struct dmctx *bbf_ctx)
{
	char cur_ch;
	int ret = 0;
	struct dmctx bbf_ctx_inst, bbf_ctx_add_obj;
	char *str = bbf_ctx->in_param, *multi_obj_str = NULL;

	INFO("Req to add object |%s|", bbf_ctx->in_param);
	memset(&bbf_ctx_inst, 0, sizeof(bbf_ctx_inst));
	bbf_sub_init(&bbf_ctx_inst);
	bbf_ctx_inst.in_param = bbf_ctx->in_param;
	memset(&bbf_ctx_add_obj, 0, sizeof(bbf_ctx_add_obj));
	bbf_sub_init(&bbf_ctx_add_obj);
	bbf_ctx_add_obj.in_param = bbf_ctx->in_param;

	while (!ret && (str = DM_STRCHR(str, '.')))
	{
		cur_ch = str[1];
		str[1] = '\0';
		ret = bbfdm_cmd_exec(&bbf_ctx_inst, BBF_INSTANCES);

		if (ret && multi_obj_str) {
			int ch = multi_obj_str[1];

			multi_obj_str[1] = '\0';
			if ((ret = bbfdm_cmd_exec(&bbf_ctx_add_obj, BBF_ADD_OBJECT))) {
				ERR("addObject: failed adding object (%s)", bbf_ctx_add_obj.in_param);
			}
			multi_obj_str[1] = ch;
		}

	    str[1] = cur_ch;
	    if ( cur_ch >= '1' && cur_ch <= '9')
		    multi_obj_str = str;
	    else
		    multi_obj_str = NULL;
	    str++;
    }
    bbf_sub_cleanup(&bbf_ctx_inst);
    bbf_sub_cleanup(&bbf_ctx_add_obj);

    return ret;
}

int del_object(char *obj_path)
{
	struct dmctx bbf_ctx;
	int ret = 0;

	memset(&bbf_ctx, 0, sizeof(bbf_ctx));
	bbf_init(&bbf_ctx);
	bbf_ctx.in_param = obj_path;

	INFO("Req to del object |%s|", obj_path);
	if ((ret = bbfdm_cmd_exec(&bbf_ctx, BBF_DEL_OBJECT)))
		ERR("Failed deleting (%s)", obj_path);

	bbf_cleanup(&bbf_ctx);

	return ret;
}

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

	if (jmsg == NULL || jreply == NULL) {
		ERR("getParameters cb: invalid memory");
		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, DELETE_REQUEST_MESSAGE,
			&param_request) != RETURN_OK) {
			ERR("deleteObject cb: failed getting parameter");
			return RETURN_ERR;
		}

		ret = del_object(param_request.name);
		if (json_hal_add_result_status(jreply, ret ? RESULT_FAILURE : RESULT_SUCCESS) != RETURN_OK) {
			ERR("deleteObject cb: failed adding response");
			return RETURN_ERR;
		}
	}

	restart_services();

	return RETURN_OK;
}