/*
 * Purple Zulip - Zulip Protocol Plugin
 * Copyright (C) Pidgin Developers <devel@pidgin.im>
 *
 * Purple Zulip is the legal property of its developers, whose names are too
 * numerous to list here. Please refer to the COPYRIGHT file distributed with
 * this source distribution.
 *
 * This plugin is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This plugin 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 General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this plugin; if not, see <https://www.gnu.org/licenses/>.
 */

#include <json-glib/json-glib.h>

#include <birb.h>

#include "purplezulipevents.h"

/******************************************************************************
 * Event
 *****************************************************************************/
PurpleZulipEvent *
purple_zulip_event_copy(PurpleZulipEvent *event) {
	PurpleZulipEvent *copy = NULL;

	g_return_val_if_fail(event != NULL, NULL);

	copy = g_new0(PurpleZulipEvent, 1);

	copy->id = event->id;
	copy->type = g_strdup(event->type);

	return copy;
}

void
purple_zulip_event_free(PurpleZulipEvent *event) {
	g_return_if_fail(event != NULL);

	g_free(event->type);

	g_free(event);
}

static gpointer
purple_zulip_event_deserialize(JsonNode *node) {
	PurpleZulipEvent *event = NULL;
	JsonNode *event_data = NULL;
	JsonObject *object = NULL;
	const char *value = NULL;

	event = g_new(PurpleZulipEvent, 1);

	object = json_node_get_object(node);

	event->id = json_object_get_int_member_with_default(object, "id", -1);

	value = json_object_get_string_member_with_default(object, "type", NULL);
	event->type = g_strdup(value);

	if(birb_str_equal(event->type, PURPLE_ZULIP_EVENT_MESSAGE)) {
		event_data = json_object_get_member(object, "message");

		event->message = json_boxed_deserialize(PURPLE_ZULIP_TYPE_MESSAGE,
		                                        event_data);
	}

	return event;
}

G_DEFINE_BOXED_TYPE_WITH_CODE(PurpleZulipEvent,
                              purple_zulip_event,
                              purple_zulip_event_copy,
                              purple_zulip_event_free,
                              json_boxed_register_deserialize_func(g_define_type_id,
                                                                   JSON_NODE_OBJECT,
                                                                   purple_zulip_event_deserialize))
