#include "dbh_config.h"

#include <stdbool.h>
#include <string.h>

#include "dynbh.h"

#if PERSIST_CONTROLLER
int set_value_by_string(const char *package, const char *section,
		const char *key, const char *value, enum uci_option_type type)
{
	struct uci_ptr ptr = {0};
	struct uci_context *ctx;
	int rv = 0;

	ctx = uci_alloc_context();
	if (!ctx)
		return -1;

	ptr.package = package;
	ptr.section = section;
	ptr.option = key;
	ptr.value = value;

	if (type == UCI_TYPE_STRING)
		rv = uci_set(ctx, &ptr);

	if (type == UCI_TYPE_LIST)
		rv = uci_add_list(ctx, &ptr);

	uci_commit(ctx, &ptr.p, false);

	uci_free_context(ctx);
	return rv;
}

static int dbh_config_get_controller_select(struct dynbh_ctx *ctx,
				       struct uci_section *s)
{
	enum {
		CTRL_SELECT_LOCAL,
		CTRL_SELECT_MODE,
		CTRL_SELECT_PROBE_INT,
		CTRL_SELECT_RETRY_INT,
		NUM_CTRL_SELECT_POLICIES,
	};

	const struct uci_parse_option opts[] = {
		{ .name = "local", .type = UCI_TYPE_STRING },
		{ .name = "id", .type = UCI_TYPE_STRING },
		{ .name = "probe_int", .type = UCI_TYPE_STRING },
		{ .name = "retry_int", .type = UCI_TYPE_STRING },

	};

	struct uci_option *tb[NUM_CTRL_SELECT_POLICIES];

	uci_parse_section(s, opts, NUM_CTRL_SELECT_POLICIES, tb);

	if (tb[CTRL_SELECT_MODE]) {
		const char *mode = tb[CTRL_SELECT_MODE]->v.string;

		if (!strncmp(mode, "auto", 4)) {
			ctx->discovery_mode = DYNAMIC_CNTLR_MODE_AUTO;
		} else if (!strncmp(mode, "disabled", 4)) {
			ctx->discovery_mode = DYNAMIC_CNTLR_MODE_DISABLED;
		} else if (!strncmp(mode, "controller", 4)) {
			ctx->discovery_mode = DYNAMIC_CNTLR_MODE_CONTROLLER;
		}
	} else {
		ctx->discovery_mode = DYNAMIC_CNTLR_MODE_AUTO;
	}

	return 0;
}


int dbh_config_load(struct dynbh_ctx *cfg)
{
	struct uci_context *ctx;
	struct uci_package *pkg;
	struct uci_element *e;


	ctx = uci_alloc_context();
	if (!ctx)
		return -1;

	if (uci_load(ctx, "mapagent", &pkg)) {
		uci_free_context(ctx);
		return -1;
	}

	uci_foreach_element(&pkg->sections, e) {
		struct uci_section *s = uci_to_section(e);

		if (!strcmp(s->type, "controller_select"))
			dbh_config_get_controller_select(cfg, s);
	}

	uci_free_context(ctx);
	return 0;
}
#endif
