/*!
 * 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: 18/08/2017
 */

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

#include <string.h>

extern "C" {
#include <libubox/blobmsg_json.h>
}

#include "ubus-cpp/ubus-event-receiver.h"

/*------------------------------- GLOBALS ----------------------------------*/

/*--------------------------------- DEFINES ---------------------------------*/

/*!  ----------------------------------------------------------------------------
 *  @fn receive_event
 *
 *  @brief callback called when the event arrive.
 */
static void receive_event(struct ubus_context *a_ctx, struct ubus_event_handler *an_ev,
						  const char *a_type, struct blob_attr *a_msg)
{
	char *the_string;
	UBusEventReceiver *the_receiver = static_cast<UBusEventReceiver *>(an_ev);
	the_string = blobmsg_format_json(a_msg, true);

	the_receiver->handle_event(a_type, the_string);

	free(the_string);
}

/*!  ----------------------------------------------------------------------------
 *  @fn UBusEventReceiver
 *
 *  @brief Constructor of the UBus Event Receiver
 */
UBusEventReceiver::UBusEventReceiver(void)
{
	obj = {0};
	cb = receive_event;
}

/*!  ----------------------------------------------------------------------------
 *  @fn ~UBusEventReceiver
 *
 *  @brief Destructor of of the UBus Event Receiver
 */
UBusEventReceiver::~UBusEventReceiver(void)
{
}

/*!  ----------------------------------------------------------------------------
 *  @fn register_event
 *
 *  @brief register to an ubus event type.
 */
int UBusEventReceiver::register_event(struct ubus_context *a_ctx, const std::string &an_event)
{
	return ubus_register_event_handler(a_ctx, this, an_event.c_str());
}

/*!  ----------------------------------------------------------------------------
 *  @fn unregister_event
 *
 *  @brief un register to an ubus event type.
 */
int UBusEventReceiver::unregister_event(struct ubus_context *a_ctx)
{
	return ubus_unregister_event_handler(a_ctx, this);
}
