/*
 * Ibis - IRCv3 Library
 * Copyright (C) 2022-2025 Ibis Developers
 *
 * Ibis 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 library 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 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include <gio/gio.h>

#include "ibisbatch.h"

#include "ibisconstants.h"
#include "ibisstring.h"

struct _IbisBatch {
	GObject parent;

	char *reference_tag;
	char *parent_tag;
	char *batch_type;

	GPtrArray *messages;
};

enum {
	PROP_0,
	PROP_REFERENCE_TAG,
	PROP_PARENT_TAG,
	PROP_BATCH_TYPE,
	N_PROPERTIES,
};
static GParamSpec *properties[N_PROPERTIES] = {NULL, };

G_DEFINE_QUARK(ibis-batch-add-message-error, ibis_batch_add_message_error)
G_DEFINE_QUARK(ibis-batch-parse-error, ibis_batch_parse_error)

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
ibis_batch_set_batch_type(IbisBatch *batch, const char *batch_type) {
	g_return_if_fail(IBIS_IS_BATCH(batch));
	g_return_if_fail(!ibis_str_is_empty(batch_type));

	if(g_set_str(&batch->batch_type, batch_type)) {
		g_object_notify_by_pspec(G_OBJECT(batch), properties[PROP_BATCH_TYPE]);
	}
}

static void
ibis_batch_set_parent_tag(IbisBatch *batch, const char *parent_tag) {
	g_return_if_fail(IBIS_IS_BATCH(batch));

	if(g_set_str(&batch->parent_tag, parent_tag)) {
		g_object_notify_by_pspec(G_OBJECT(batch), properties[PROP_PARENT_TAG]);
	}
}

static void
ibis_batch_set_reference_tag(IbisBatch *batch, const char *reference_tag) {
	g_return_if_fail(IBIS_IS_BATCH(batch));
	g_return_if_fail(!ibis_str_is_empty(reference_tag));

	if(g_set_str(&batch->reference_tag, reference_tag)) {
		g_object_notify_by_pspec(G_OBJECT(batch),
		                         properties[PROP_REFERENCE_TAG]);
	}
}

/******************************************************************************
 * GListModel Implementation
 *****************************************************************************/
static GType
ibis_batch_get_item_type(G_GNUC_UNUSED GListModel *model) {
	return IBIS_TYPE_MESSAGE;
}

static guint
ibis_batch_get_n_items(GListModel *model) {
	IbisBatch *batch = IBIS_BATCH(model);

	return batch->messages->len;
}

static gpointer
ibis_batch_get_item(GListModel *model, guint position) {
	IbisBatch *batch = IBIS_BATCH(model);
	IbisMessage *message = NULL;

	if(position < batch->messages->len) {
		message = g_ptr_array_index(batch->messages, position);

		if(IBIS_IS_MESSAGE(message)) {
			g_object_ref(message);
		}
	}

	return message;
}

static void
ibis_batch_list_model_iface_init(GListModelInterface *iface) {
	iface->get_item_type = ibis_batch_get_item_type;
	iface->get_n_items = ibis_batch_get_n_items;
	iface->get_item = ibis_batch_get_item;
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE_WITH_CODE(IbisBatch,
                              ibis_batch,
                              G_TYPE_OBJECT,
                              G_IMPLEMENT_INTERFACE(G_TYPE_LIST_MODEL,
                                                    ibis_batch_list_model_iface_init))

static void
ibis_batch_finalize(GObject *obj) {
	IbisBatch *batch = IBIS_BATCH(obj);

	g_clear_pointer(&batch->batch_type, g_free);
	g_clear_pointer(&batch->parent_tag, g_free);
	g_clear_pointer(&batch->reference_tag, g_free);
	g_clear_pointer(&batch->messages, g_ptr_array_unref);

	G_OBJECT_CLASS(ibis_batch_parent_class)->finalize(obj);
}

static void
ibis_batch_get_property(GObject *obj, guint param_id, GValue *value,
                        GParamSpec *pspec)
{
	IbisBatch *batch = IBIS_BATCH(obj);

	switch(param_id) {
	case PROP_BATCH_TYPE:
		g_value_set_string(value, ibis_batch_get_batch_type(batch));
		break;
	case PROP_PARENT_TAG:
		g_value_set_string(value, ibis_batch_get_parent_tag(batch));
		break;
	case PROP_REFERENCE_TAG:
		g_value_set_string(value, ibis_batch_get_reference_tag(batch));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
ibis_batch_set_property(GObject *obj, guint param_id, const GValue *value,
                        GParamSpec *pspec)
{
	IbisBatch *batch = IBIS_BATCH(obj);

	switch(param_id) {
	case PROP_BATCH_TYPE:
		ibis_batch_set_batch_type(batch, g_value_get_string(value));
		break;
	case PROP_PARENT_TAG:
		ibis_batch_set_parent_tag(batch, g_value_get_string(value));
		break;
	case PROP_REFERENCE_TAG:
		ibis_batch_set_reference_tag(batch, g_value_get_string(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
ibis_batch_init(IbisBatch *batch) {
	batch->messages = g_ptr_array_new_full(1, g_object_unref);
}

static void
ibis_batch_class_init(IbisBatchClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize = ibis_batch_finalize;
	obj_class->get_property = ibis_batch_get_property;
	obj_class->set_property = ibis_batch_set_property;

	/**
	 * IbisBatch:reference-tag
	 *
	 * The reference tag of the batch.
	 *
	 * Since: 0.12
	 */
	properties[PROP_REFERENCE_TAG] = g_param_spec_string(
		"reference-tag", NULL, NULL,
		NULL,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);

	/**
	 * IbisBatch:parent-tag
	 *
	 * The parent tag of the batch.
	 *
	 * Since: 0.12
	 */
	properties[PROP_PARENT_TAG] = g_param_spec_string(
		"parent-tag", NULL, NULL,
		NULL,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);

	/**
	 * IbisBatch:batch-type:
	 *
	 * The type of the batch.
	 *
	 * Since: 0.12
	 */
	properties[PROP_BATCH_TYPE] = g_param_spec_string(
		"batch-type", NULL, NULL,
		NULL,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
ibis_batch_add_message(IbisBatch *batch, IbisMessage *message, GError **error)
{
	IbisTags *tags = NULL;
	const char *message_batch = NULL;
	guint position = 0;

	g_return_val_if_fail(IBIS_IS_BATCH(batch), FALSE);
	g_return_val_if_fail(IBIS_IS_MESSAGE(message), FALSE);

	tags = ibis_message_get_tags(message);
	message_batch = ibis_tags_lookup(tags, IBIS_TAG_BATCH);
	if(!ibis_str_equal(batch->reference_tag, message_batch)) {
		g_set_error(error,
		            IBIS_BATCH_ADD_MESSAGE_ERROR,
		            IBIS_BATCH_ADD_MESSAGE_ERROR_INVALID_REFERENCE_TAG,
		            "invalid reference tag '%s', expected '%s'",
		            message_batch,
		            batch->reference_tag);

		return FALSE;
	}

	/* Store the length as the position for the new item. */
	position = batch->messages->len;
	g_ptr_array_add(batch->messages, g_object_ref(message));

	/* Use the position to notify that we added an item at that position. */
	g_list_model_items_changed(G_LIST_MODEL(batch), position, 0, 1);

	return TRUE;
}

const char *
ibis_batch_get_batch_type(IbisBatch *batch) {
	g_return_val_if_fail(IBIS_IS_BATCH(batch), NULL);

	return batch->batch_type;
}

const char *
ibis_batch_get_parent_tag(IbisBatch *batch) {
	g_return_val_if_fail(IBIS_IS_BATCH(batch), NULL);

	return batch->parent_tag;
}

const char *
ibis_batch_get_reference_tag(IbisBatch *batch) {
	g_return_val_if_fail(IBIS_IS_BATCH(batch), NULL);

	return batch->reference_tag;
}

const char *
ibis_batch_is_end(IbisMessage *message) {
	GStrv params = NULL;
	const char *command = NULL;
	const char *reference_tag = NULL;
	guint n_params = 0;

	g_return_val_if_fail(IBIS_IS_MESSAGE(message), NULL);

	command = ibis_message_get_command(message);
	if(!ibis_str_equal(IBIS_MSG_BATCH, command)) {
		return NULL;
	}

	params = ibis_message_get_params(message);
	if(params != NULL) {
		n_params = g_strv_length(params);
	}

	if(n_params != 1) {
		return NULL;
	}

	reference_tag = params[0];
	if(reference_tag[0] == '-') {
		if(!ibis_str_is_empty(reference_tag + 1)) {
			return reference_tag + 1;
		}
	}

	return NULL;
}

IbisBatch *
ibis_batch_parse(IbisMessage *message, GError **error) {
	IbisTags *tags = NULL;
	GStrv params = NULL;
	const char *batch_type = NULL;
	const char *parent_tag = NULL;
	const char *reference_tag = NULL;
	guint n_params = 0;

	g_return_val_if_fail(IBIS_IS_MESSAGE(message), NULL);

	params = ibis_message_get_params(message);
	if(params != NULL) {
		n_params = g_strv_length(params);
	}

	if(n_params < 2) {
		g_set_error(error,
		            IBIS_BATCH_PARSE_ERROR,
		            IBIS_BATCH_PARSE_ERROR_NOT_ENOUGH_PARAMS,
		            "expected at least 2 parameters but only found %u",
		            n_params);

		return NULL;
	}

	/* Make sure the reference tag starts with a +. */
	reference_tag = params[0];
	if(reference_tag[0] != '+') {
		g_set_error(error,
		            IBIS_BATCH_PARSE_ERROR,
		            IBIS_BATCH_PARSE_ERROR_INVALID_REFERENCE_TAG,
		            "invalid reference tag '%s'",
		            reference_tag);

		return NULL;
	}

	/* Now make sure we have an actual reference tag. */
	if(ibis_str_is_empty(reference_tag + 1)) {
		g_set_error(error,
		            IBIS_BATCH_PARSE_ERROR,
		            IBIS_BATCH_PARSE_ERROR_INVALID_REFERENCE_TAG,
		            "invalid reference tag '%s'",
		            reference_tag);

		return NULL;
	}
	reference_tag = reference_tag + 1;

	batch_type = params[1];
	if(ibis_str_is_empty(batch_type)) {
		g_set_error(error,
		            IBIS_BATCH_PARSE_ERROR,
		            IBIS_BATCH_PARSE_ERROR_INVALID_BATCH_TYPE,
		            "invalid batch type '%s'",
		            batch_type);

		return NULL;
	}

	tags = ibis_message_get_tags(message);
	parent_tag = ibis_tags_lookup(tags, IBIS_TAG_BATCH);

	return g_object_new(
		IBIS_TYPE_BATCH,
		"batch-type", batch_type,
		"parent-tag", parent_tag,
		"reference-tag", reference_tag,
		NULL);
}
