#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <libubus.h>
#include <libubox/blobmsg_json.h>
#include <libubox/blobmsg.h>

#include <json-c/json.h>
#include "timer.h"
#include "wfa_delm.h"

extern struct bh_topology_dev wifi_ifs[WIFI_DEVICE_MAX_NUM];

int delm_dump(struct ubus_context *ctx, struct ubus_object *obj,
		struct ubus_request_data *req, const char *method,
		struct blob_attr *msg);

int delm_refresh(struct ubus_context *ctx, struct ubus_object *obj,
		struct ubus_request_data *req, const char *method,
		struct blob_attr *msg);

// int get_wifi_interfaces(struct ubus_context *ctx, struct bh_topology_dev *ifs);

int delm_init(void **priv, void *cfg);

int delm_exit(void *priv);

static int group_setup(void **state)
{
	void *ptr;
	struct delm_private *p;
	struct ubus_context *ctx;
	struct delm_config c = {0};

	ctx = ubus_connect(NULL);
	if (!ctx) {
		fprintf(stderr, "Failed to connect to ubus\n");
		return -1;
	}

#if 0
	get_wifi_interfaces(ctx, wifi_ifs);
	ubus_free(ctx);
#endif
	c.is_collector = 0;
	c.profile = MULTIAP_PROFILE_2;
	c.uctx = ctx;

	delm_init(&ptr, &c);
	sleep(1);

	p = (struct delm_private *)ptr;
	p->obj.name = "wifi.data";
	*state = p;
	return 0;
}

static int setup(void **state)
{
	return 0;
}

static int group_teardown(void **state)
{
	struct delm_private *p = (struct delm_private *) *state;

	delm_exit(p);
	remove("/tmp/test.log");
	return 0;
}

static void test_api_wfadata_dump(void **state)
{
	struct json_object *jobj, *tmp, *array_obj, *wfa_data_obj, *device_obj;

	struct delm_private *p = (struct delm_private *) *state;
	struct ubus_object *obj = &p->obj;

	delm_dump(NULL, obj, NULL, "dump", NULL);
	jobj = json_object_from_file("/tmp/test.log");
	assert_non_null(jobj);

	array_obj = json_object_object_get(jobj, "data");
	wfa_data_obj = json_object_array_get_idx(array_obj, 0);

	tmp = json_object_object_get(wfa_data_obj, "wfa-dataelements:Network");

	device_obj = json_object_object_get(tmp, "DeviceList");
	assert_non_null(device_obj);
	json_object_put(jobj);
}

static void test_api_wfadata_refresh(void **state)
{
	struct delm_private *p = (struct delm_private *) *state;
	struct ubus_object *obj = &p->obj;

	delm_refresh(NULL, obj, NULL, "refresh", NULL);
	printf("Wait to sync\n");
	sleep(2);
}

int ubus_send_reply(struct ubus_context *ctx, struct ubus_request_data *req,
		struct blob_attr *msg)
{
	char *str;
	FILE *fp;


	if (!msg)
		return -1;

	fp = fopen("/tmp/test.log", "w");
	if (!fp) {
		printf("failed to open file\n");
		return -1;
	}

	str = blobmsg_format_json_indent(msg, true, -1);
	fprintf(fp, "%s", str);

	fclose(fp);
	free(str);
	return 0;
}

int main(void)
{
	const struct CMUnitTest tests[] = {
		cmocka_unit_test_setup(test_api_wfadata_dump, setup),
		cmocka_unit_test_setup(test_api_wfadata_refresh, setup)
	};

	return cmocka_run_group_tests(tests, group_setup, group_teardown);
}
