#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "utils/debug.h"
#include "cntlr.h"
#include "cntlr_apis.h"
#include "timer.h"
#include "timer_impl.h"

int cntlr_son_response_cb(void *cntlr, const char *json)
{
	cntlr_err(LOG_SON, "%s: ------------>\n", __func__);
	struct controller *c = (struct controller *)cntlr;

	if (json)
		cntlr_err(LOG_SON, "%s: response = %s\n", __func__, json);

	// TODO: parse received topology json
	// and issue bsta steer to the appropriate agents.
	
	UNUSED(c);
	return 0;
}

#define CNTLR_PLUGIN_PATH		"/usr/lib/mapcontroller"

int cntlr_son_init(void *cntlr)
{
	struct controller *c = (struct controller *)cntlr;
	char abspath[256] = {0};
	int flags = 0;
	void *h;

	flags |= RTLD_NOW | RTLD_GLOBAL;
	snprintf(abspath, sizeof(abspath) - 1, "%s/%s", CNTLR_PLUGIN_PATH, "son.so");
	h = dlopen(abspath, flags);
	if (!h) {
		cntlr_err(LOG_SON, "%s: Error: %s\n", __func__, dlerror());
		return -1;
	}

	c->son = h;
	c->son_doit = dlsym(h, "cntlr_son_plugin_doit");
	if (!c->son_doit) {
		cntlr_err(LOG_SON, "%s: Error: %s\n", __func__, dlerror());
		dlclose(h);
		c->son = NULL;
		return -1;
	}

	return 0;
}

void cntlr_son_exit(void *cntlr)
{
	struct controller *c = (struct controller *)cntlr;

	if (c->son) {
		dlclose(c->son);
		c->son = NULL;
	}
}
