/*!
 * Copyright (c) 2015-2018, NADAL Jean-Baptiste. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 *
 * @Author:  NADAL Jean-Baptiste
 * @date: 15/06/2017
 */

/*------------------------------- INCLUDES ----------------------------------*/

#include <libubus.h>

#include <uhttpd/uhttpd.h>
#include <uhttpd/plugin.h>

/*--------------------------------- PLUGINS ----------------------------------*/

extern struct ubus_context *get_uhttp_server_ctx(void);
extern int uhttp_server_setup(struct ubus_context *a_ctx, const struct uhttpd_ops *an_ops, const char *a_config_dir_path);
extern bool uhttp_server_check_url(const char *an_url);
extern void uhttp_server_handle_request(struct client *a_cl, char *an_url, struct path_info *a_pi);

bool uhttp_server_check_path(struct path_info *pi, const char *url)
{
	// printf ("uhttp_server_check_path: url: %s\n", url);
	return true;
}

/*!  ---------------------------------------------------------------------------- */

static struct dispatch_handler g_ubus_dispatch = {

	.check_url = uhttp_server_check_url,
	.handle_request = uhttp_server_handle_request,
};

/*!  ----------------------------------------------------------------------------
 *  @fn uh_awox_api_plugin_init
 *
 *  @brief 
 */
static int uh_awox_api_plugin_init(const struct uhttpd_ops *an_ops, struct config *a_conf)
{
	struct ubus_context *the_ctx;

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

	an_ops->dispatch_add(&g_ubus_dispatch);

	uloop_done();

	return uhttp_server_setup(the_ctx, an_ops, a_conf->ubus_prefix);
}

/*!  ----------------------------------------------------------------------------
 *  @fn uh_awox_api_plugin_post_init
 *
 *  @brief 
 */
static void uh_awox_api_plugin_post_init(void)
{
	ubus_add_uloop(get_uhttp_server_ctx());
}

/*!  ---------------------------------------------------------------------------- */

struct uhttpd_plugin uhttpd_plugin = {

	.init = uh_awox_api_plugin_init,
	.post_init = uh_awox_api_plugin_post_init,
};
