/*
 * Pidgin - Internet Messenger
 * Copyright (C) Pidgin Developers <devel@pidgin.im>
 *
 * Pidgin 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 program 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 program 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 program; if not, see <https://www.gnu.org/licenses/>.
 */

#ifdef G_LOG_DOMAIN
# undef G_LOG_DOMAIN
#endif /* G_LOG_DOMAIN */
#define G_LOG_DOMAIN "PidginSoundManager"

#include <birb.h>

#include "pidginsoundmanager.h"

struct _PidginSoundManager {
	GObject parent;

	PurpleCore *core;

	gboolean sounds_enabled;

	gboolean new_message_enabled;
	GtkMediaStream *new_message_stream_default;
	GtkMediaStream *new_message_stream;
};

enum {
	PROP_0,
	PROP_CORE,
	PROP_SOUNDS_ENABLED,
	PROP_NEW_MESSAGE_ENABLED,
	PROP_NEW_MESSAGE_STREAM,
	N_PROPERTIES,
};
static GParamSpec *properties[N_PROPERTIES] = {NULL, };

#define RESOURCE_PATH "/im/pidgin/Pidgin3/sounds/"

/******************************************************************************
 * Callbacks
 *****************************************************************************/
static void
pidgin_sounds_manager_play_sound(PidginSoundManager *manager,
                                 GtkMediaStream *stream,
                                 GtkMediaStream *fallback)
{
	GtkMediaStream *candidate = NULL;

	if(!manager->sounds_enabled) {
		return;
	}

	candidate = stream;
	if(!GTK_IS_MEDIA_STREAM(candidate)) {
		candidate = fallback;
	}

	if(!gtk_media_stream_get_playing(candidate)) {
		gtk_media_stream_seek(candidate, 0);
		gtk_media_stream_play(candidate);
	}
}

static void
pidgin_sound_manager_new_message_cb(G_GNUC_UNUSED PurpleConversationManager *conversation_manager,
                                    PurpleConversation *conversation,
                                    G_GNUC_UNUSED PurpleMessage *message,
                                    gpointer data)
{
	PidginSoundManager *manager = data;
	PurpleConversationType type = PURPLE_CONVERSATION_TYPE_UNSET;

	if(!manager->new_message_enabled) {
		return;
	}

	type = purple_conversation_get_conversation_type(conversation);
	if(type == PURPLE_CONVERSATION_TYPE_UNSET) {
		return;
	}

	pidgin_sounds_manager_play_sound(manager, manager->new_message_stream,
	                                 manager->new_message_stream_default);
}

/******************************************************************************
 * Helpers
 *****************************************************************************/
static gboolean
pidgin_sound_manager_map_get_filename(GValue *value, GVariant *variant,
                                      G_GNUC_UNUSED gpointer data)
{
	GtkMediaStream *stream = NULL;
	const char *filename = NULL;

	filename = g_variant_get_string(variant, NULL);
	if(!birb_str_is_empty(filename)) {
		stream = gtk_media_file_new_for_filename(filename);
	}

	g_value_set_object(value, stream);

	return TRUE;
}

static GVariant *
pidgin_sound_manager_map_set_filename(const GValue *value,
                                      const GVariantType *expected,
                                      G_GNUC_UNUSED gpointer data)
{
	GtkMediaStream *stream = NULL;
	GVariant *variant = NULL;

	if(!g_variant_type_equal(expected, G_VARIANT_TYPE_STRING)) {
		return NULL;
	}

	stream = g_value_get_object(value);
	if(GTK_IS_MEDIA_FILE(stream)) {
		GFile *file = NULL;

		file = gtk_media_file_get_file(GTK_MEDIA_FILE(stream));
		variant = g_variant_new_take_string(g_file_get_path(file));
	}

	return variant;
}

static void
pidgin_sound_manager_bind_settings(PidginSoundManager *manager) {
	GSettings *settings = NULL;

	settings = purple_core_new_settings(manager->core,
	                                    "im.pidgin.Pidgin3.Sounds");

	g_settings_bind(settings, "sounds-enabled",
	                manager, "sounds-enabled",
	                G_SETTINGS_BIND_DEFAULT);

	g_settings_bind(settings, "new-message-enabled",
	                manager, "new-message-enabled",
	                G_SETTINGS_BIND_DEFAULT);
	g_settings_bind_with_mapping(settings, "new-message-filename",
	                             manager, "new-message-stream",
	                             G_SETTINGS_BIND_DEFAULT,
	                             pidgin_sound_manager_map_get_filename,
	                             pidgin_sound_manager_map_set_filename,
	                             NULL, NULL);

	g_clear_object(&settings);
}

static void
pidgin_sound_manager_setup_events(PidginSoundManager *manager) {
	PurpleConversationManager *conversation_manager = NULL;

	conversation_manager = purple_core_get_conversation_manager(manager->core);
	g_signal_connect_object(conversation_manager, "conversation-new-message",
	                        G_CALLBACK(pidgin_sound_manager_new_message_cb),
	                        manager, G_CONNECT_DEFAULT);
}

static void
pidgin_sound_manager_set_core(PidginSoundManager *manager, PurpleCore *core) {
	g_return_if_fail(PIDGIN_IS_SOUND_MANAGER(manager));

	if(g_set_object(&manager->core, core)) {
		if(PURPLE_IS_CORE(manager->core)) {
			pidgin_sound_manager_bind_settings(manager);
			pidgin_sound_manager_setup_events(manager);
		}
	}
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE(PidginSoundManager, pidgin_sound_manager, G_TYPE_OBJECT)

static void
pidgin_sound_manager_finalize(GObject *obj) {
	PidginSoundManager *manager = PIDGIN_SOUND_MANAGER(obj);

	g_clear_object(&manager->core);
	g_clear_object(&manager->new_message_stream);
	g_clear_object(&manager->new_message_stream_default);

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

static void
pidgin_sound_manager_get_property(GObject *obj, guint param_id, GValue *value,
                                  GParamSpec *pspec)
{
	PidginSoundManager *manager = PIDGIN_SOUND_MANAGER(obj);

	switch(param_id) {
	case PROP_NEW_MESSAGE_ENABLED:
		g_value_set_boolean(value,
		                    pidgin_sound_manager_get_new_message_enabled(manager));
		break;
	case PROP_NEW_MESSAGE_STREAM:
		g_value_set_object(value,
		                   pidgin_sound_manager_get_new_message_stream(manager));
		break;
	case PROP_SOUNDS_ENABLED:
		g_value_set_boolean(value,
		                    pidgin_sound_manager_get_sounds_enabled(manager));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
pidgin_sound_manager_set_property(GObject *obj, guint param_id,
                                  const GValue *value, GParamSpec *pspec)
{
	PidginSoundManager *manager = PIDGIN_SOUND_MANAGER(obj);

	switch(param_id) {
	case PROP_CORE:
		pidgin_sound_manager_set_core(manager, g_value_get_object(value));
		break;
	case PROP_NEW_MESSAGE_ENABLED:
		pidgin_sound_manager_set_new_message_enabled(manager,
		                                             g_value_get_boolean(value));
		break;
	case PROP_NEW_MESSAGE_STREAM:
		pidgin_sound_manager_set_new_message_stream(manager,
		                                            g_value_get_object(value));
		break;
	case PROP_SOUNDS_ENABLED:
		pidgin_sound_manager_set_sounds_enabled(manager,
		                                        g_value_get_boolean(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
pidgin_sound_manager_init(PidginSoundManager *manager) {
	GtkMediaStream *stream = NULL;

	manager->new_message_enabled = TRUE;
	stream = gtk_media_file_new_for_resource("/im/pidgin/Pidgin3/sounds/receive.ogg");
	manager->new_message_stream_default = stream;

	manager->sounds_enabled = TRUE;
}

static void
pidgin_sound_manager_class_init(PidginSoundManagerClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);

	obj_class->finalize = pidgin_sound_manager_finalize;
	obj_class->get_property = pidgin_sound_manager_get_property;
	obj_class->set_property = pidgin_sound_manager_set_property;

	/**
	 * PidginSoundManager:core:
	 *
	 * The core instance that the manager is working with.
	 *
	 * Since: 3.0
	 */
	properties[PROP_CORE] = g_param_spec_object(
		"core", NULL, NULL,
		PURPLE_TYPE_CORE,
		G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);

	/**
	 * PidginSoundManager:new-message-enabled:
	 *
	 * Whether or not to play a sound when a new message arrives.
	 *
	 * Since: 3.0
	 */
	properties[PROP_NEW_MESSAGE_ENABLED] = g_param_spec_boolean(
		"new-message-enabled", NULL, NULL,
		TRUE,
		G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_EXPLICIT_NOTIFY);

	/**
	 * PidginSoundManager:new-message-stream:
	 *
	 * The stream to play for new messages.
	 *
	 * If this is null, the default sound will be played.
	 *
	 * Since: 3.0
	 */
	properties[PROP_NEW_MESSAGE_STREAM] = g_param_spec_object(
		"new-message-stream", NULL, NULL,
		GTK_TYPE_MEDIA_STREAM,
		G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS |
		G_PARAM_EXPLICIT_NOTIFY);

	/**
	 * PidginSoundManager:sounds-enabled:
	 *
	 * Whether or not event sounds are enabled.
	 *
	 * Since: 3.0
	 */
	properties[PROP_SOUNDS_ENABLED] = g_param_spec_boolean(
		"sounds-enabled", NULL, NULL,
		TRUE,
		G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_EXPLICIT_NOTIFY);

	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
gboolean
pidgin_sound_manager_get_new_message_enabled(PidginSoundManager *manager) {
	g_return_val_if_fail(PIDGIN_IS_SOUND_MANAGER(manager), FALSE);

	return manager->new_message_enabled;
}

GtkMediaStream *
pidgin_sound_manager_get_new_message_stream(PidginSoundManager *manager) {
	g_return_val_if_fail(PIDGIN_IS_SOUND_MANAGER(manager), NULL);

	return manager->new_message_stream;
}

gboolean
pidgin_sound_manager_get_sounds_enabled(PidginSoundManager *manager) {
	g_return_val_if_fail(PIDGIN_IS_SOUND_MANAGER(manager), FALSE);

	return manager->sounds_enabled;
}

PidginSoundManager *
pidgin_sound_manager_new(PurpleCore *core) {
	g_return_val_if_fail(PURPLE_IS_CORE(core), NULL);

	return g_object_new(PIDGIN_TYPE_SOUND_MANAGER,
	                    "core", core,
	                    NULL);
}

void
pidgin_sound_manager_set_new_message_enabled(PidginSoundManager *manager,
                                             gboolean new_message_enabled)
{
	g_return_if_fail(PIDGIN_IS_SOUND_MANAGER(manager));

	if(manager->new_message_enabled != new_message_enabled) {
		manager->new_message_enabled = new_message_enabled;

		g_object_notify_by_pspec(G_OBJECT(manager),
		                         properties[PROP_NEW_MESSAGE_ENABLED]);
	}
}

void
pidgin_sound_manager_set_new_message_stream(PidginSoundManager *manager,
                                            GtkMediaStream *stream)
{
	g_return_if_fail(PIDGIN_IS_SOUND_MANAGER(manager));

	if(g_set_object(&manager->new_message_stream, stream)) {
		g_object_notify_by_pspec(G_OBJECT(manager),
		                         properties[PROP_NEW_MESSAGE_STREAM]);
	}
}

void
pidgin_sound_manager_set_sounds_enabled(PidginSoundManager *manager,
                                        gboolean sounds_enabled)
{
	g_return_if_fail(PIDGIN_IS_SOUND_MANAGER(manager));

	if(manager->sounds_enabled != sounds_enabled) {
		manager->sounds_enabled = sounds_enabled;

		g_object_notify_by_pspec(G_OBJECT(manager),
		                         properties[PROP_SOUNDS_ENABLED]);
	}
}
