/*
 * 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/>.
 */

#include <glib/gi18n-lib.h>

#include <birb.h>

#include "pidginscheduler.h"

struct _PidginScheduler {
	GtkWindow parent;

	/* Properties */
	PurpleScheduler *scheduler;

	/* Bound objects */
	GListModel *model;
	GtkFilter *filter;
	GtkWidget *search_entry;
	GtkSorter *sorter;
};

enum {
	PROP_0,
	PROP_SCHEDULER,
	N_PROPERTIES,
};
static GParamSpec *properties[N_PROPERTIES] = {NULL, };

/******************************************************************************
 * Helpers
 *****************************************************************************/
static void
pidgin_scheduler_set_scheduler(PidginScheduler *pidgin_scheduler,
                               PurpleScheduler *purple_scheduler)
{
	g_return_if_fail(PIDGIN_IS_SCHEDULER(pidgin_scheduler));

	if(g_set_object(&pidgin_scheduler->scheduler, purple_scheduler)) {
		g_object_notify_by_pspec(G_OBJECT(pidgin_scheduler),
		                         properties[PROP_SCHEDULER]);
	}
}


static gboolean
pidgin_scheduler_filter_scheduled_tasks(GObject *item, gpointer data) {
	PidginScheduler *scheduler = data;
	PurpleScheduledTask *task = PURPLE_SCHEDULED_TASK(item);
	const char *needle = NULL;
	const char *candidate = NULL;

	needle = gtk_editable_get_text(GTK_EDITABLE(scheduler->search_entry));

	candidate = purple_scheduled_task_get_title(task);
	if(birb_str_matches(needle, candidate)) {
		return TRUE;
	}

	candidate = purple_scheduled_task_get_subtitle(task);
	if(birb_str_matches(needle, candidate)) {
		return TRUE;
	}

	candidate = purple_scheduled_task_get_task_type(task);
	if(birb_str_matches(needle, candidate)) {
		return TRUE;
	}

	return FALSE;
}

static int
pidgin_scheduler_sort_scheduled_tasks(gconstpointer a,
                                      gconstpointer b,
                                      G_GNUC_UNUSED gpointer data)
{
	PurpleScheduledTask *task_a = PURPLE_SCHEDULED_TASK((gpointer)a);
	PurpleScheduledTask *task_b = PURPLE_SCHEDULED_TASK((gpointer)b);
	PurpleScheduledTaskState state_a;
	PurpleScheduledTaskState state_b;
	GDateTime *execute_at_a = NULL;
	GDateTime *execute_at_b = NULL;

	state_a = purple_scheduled_task_get_state(task_a);
	state_b = purple_scheduled_task_get_state(task_b);

	/* Executing tasks should sort before everything else. */
	if(state_a == PURPLE_SCHEDULED_TASK_STATE_EXECUTING &&
	   state_b != PURPLE_SCHEDULED_TASK_STATE_EXECUTING)
	{
		return -1;
	}

	if(state_a != PURPLE_SCHEDULED_TASK_STATE_EXECUTING &&
	   state_b == PURPLE_SCHEDULED_TASK_STATE_EXECUTING)
	{
		return 1;
	}

	/* Scheduled tasks should sort next. */
	if(state_a == PURPLE_SCHEDULED_TASK_STATE_SCHEDULED &&
	   state_b != PURPLE_SCHEDULED_TASK_STATE_SCHEDULED)
	{
		return -1;
	}

	if(state_a != PURPLE_SCHEDULED_TASK_STATE_SCHEDULED &&
	   state_b == PURPLE_SCHEDULED_TASK_STATE_SCHEDULED)
	{
		return 1;
	}

	execute_at_a = purple_scheduled_task_get_execute_at(task_a);
	execute_at_b = purple_scheduled_task_get_execute_at(task_b);

	return birb_date_time_compare(execute_at_a, execute_at_b);
}

/******************************************************************************
 * Closures
 *****************************************************************************/
static char *
pidgin_scheduler_items_changed(G_GNUC_UNUSED PidginScheduler *scheduler,
                               guint n_items,
                               G_GNUC_UNUSED gpointer data)
{
	return g_strdup_printf(_("%u tasks"), n_items);
}

static GVariant *
pidgin_scheduler_position_to_variant(G_GNUC_UNUSED PidginScheduler *scheduler,
                                     guint position,
                                     G_GNUC_UNUSED gpointer data)
{
	return g_variant_new_uint32(position);
}

static void
pidgin_scheduler_search_changed(GtkSearchEntry *self,
                                gpointer data)
{
	PidginScheduler *scheduler = data;

	gtk_filter_changed(scheduler->filter, GTK_FILTER_CHANGE_DIFFERENT);

	/* Make sure the search widget has focus, this allows the user to clear a
	 * search that has filtered out every item in the list via their keyboard.
	 */
	if(!gtk_widget_has_focus(GTK_WIDGET(self))) {
		gtk_widget_grab_focus(GTK_WIDGET(self));
	}
}

static char *
pidgin_scheduler_task_state_changed(G_GNUC_UNUSED PidginScheduler *scheduler,
                                    PurpleScheduledTaskState state,
                                    GDateTime *execute_at,
                                    G_GNUC_UNUSED gpointer data)
{
	char *description = NULL;
	char *timestamp = NULL;

	if(execute_at != NULL) {
		timestamp = g_date_time_format_iso8601(execute_at);
	}

	if(state == PURPLE_SCHEDULED_TASK_STATE_UNSCHEDULED) {
		description = g_strdup(_("Unscheduled"));
	} else if(state == PURPLE_SCHEDULED_TASK_STATE_SCHEDULED) {
		description = g_strdup_printf(_("Scheduled for %s"), timestamp);
	} else if(state == PURPLE_SCHEDULED_TASK_STATE_CANCELLED) {
		description = g_strdup(_("Cancelled"));
	} else if(state == PURPLE_SCHEDULED_TASK_STATE_EXECUTING) {
		description = g_strdup(_("Executing"));
	} else if(state == PURPLE_SCHEDULED_TASK_STATE_EXECUTED) {
		description = g_strdup_printf(_("Executed at %s"), timestamp);
	} else {
		description = g_strdup(_("Unknown"));
	}

	g_clear_pointer(&timestamp, g_free);

	return description;
}

/******************************************************************************
 * Actions
 *****************************************************************************/
static void
pidgin_scheduler_cancel_item(GtkWidget *widget,
                             G_GNUC_UNUSED const char *action_name,
                             GVariant *parameter)
{
	PidginScheduler *scheduler = PIDGIN_SCHEDULER(widget);
	PurpleScheduledTask *task = NULL;
	guint position = 0;

	if(!g_variant_is_of_type(parameter, G_VARIANT_TYPE_UINT32)) {
		g_warning("parameter is of type %s, expected %s",
		          g_variant_get_type_string(parameter),
		          (char *)G_VARIANT_TYPE_UINT32);

		return;
	}

	position = g_variant_get_uint32(parameter);

	/* We have to pull from the model in the widget because that's the one the
	 * user is interacting with and the models will figure out the correct
	 * mapping based on their nesting.
	 */
	task = g_list_model_get_item(scheduler->model, position);
	purple_scheduled_task_cancel(task);
	g_clear_object(&task);

	/* Now tell the sorter that things changed. */
	gtk_sorter_changed(scheduler->sorter, GTK_SORTER_CHANGE_DIFFERENT);
}

/******************************************************************************
 * GObject Implementation
 *****************************************************************************/
G_DEFINE_FINAL_TYPE(PidginScheduler, pidgin_scheduler, GTK_TYPE_WINDOW)

static void
pidgin_scheduler_finalize(GObject *obj) {
	PidginScheduler *scheduler = PIDGIN_SCHEDULER(obj);

	g_clear_object(&scheduler->scheduler);

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

static void
pidgin_scheduler_get_property(GObject *obj, guint param_id, GValue *value,
                              GParamSpec *pspec)
{
	PidginScheduler *scheduler = PIDGIN_SCHEDULER(obj);

	switch(param_id) {
	case PROP_SCHEDULER:
		g_value_set_object(value, pidgin_scheduler_get_scheduler(scheduler));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
pidgin_scheduler_set_property(GObject *obj, guint param_id,
                              const GValue *value, GParamSpec *pspec)
{
	PidginScheduler *scheduler = PIDGIN_SCHEDULER(obj);

	switch(param_id) {
	case PROP_SCHEDULER:
		pidgin_scheduler_set_scheduler(scheduler, g_value_get_object(value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec);
		break;
	}
}

static void
pidgin_scheduler_init(PidginScheduler *scheduler) {
	gtk_widget_init_template(GTK_WIDGET(scheduler));

	gtk_custom_filter_set_filter_func(GTK_CUSTOM_FILTER(scheduler->filter),
	                                  (GtkCustomFilterFunc)pidgin_scheduler_filter_scheduled_tasks,
	                                  scheduler,
	                                  NULL);

	gtk_custom_sorter_set_sort_func(GTK_CUSTOM_SORTER(scheduler->sorter),
	                                pidgin_scheduler_sort_scheduled_tasks,
	                                NULL,
	                                NULL);
}

static void
pidgin_scheduler_class_init(PidginSchedulerClass *klass) {
	GObjectClass *obj_class = G_OBJECT_CLASS(klass);
	GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);

	obj_class->finalize = pidgin_scheduler_finalize;
	obj_class->get_property = pidgin_scheduler_get_property;
	obj_class->set_property = pidgin_scheduler_set_property;

	/**
	 * PidginScheduler:scheduler:
	 *
	 * The scheduler being displayed.
	 *
	 * Since: 3.0
	 */
	properties[PROP_SCHEDULER] = g_param_spec_object(
	    "scheduler", NULL, NULL,
	    PURPLE_TYPE_SCHEDULER,
	    G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_EXPLICIT_NOTIFY);

	g_object_class_install_properties(obj_class, N_PROPERTIES, properties);

	/* Actions */
	gtk_widget_class_install_action(widget_class, "item.cancel", "u",
	                                pidgin_scheduler_cancel_item);

	/* Template stuff */
	gtk_widget_class_set_template_from_resource(widget_class,
	                                            "/im/pidgin/Pidgin3/scheduler.ui");

	gtk_widget_class_bind_template_child(widget_class, PidginScheduler,
	                                     filter);
	gtk_widget_class_bind_template_child(widget_class, PidginScheduler, model);
	gtk_widget_class_bind_template_child(widget_class, PidginScheduler,
	                                     search_entry);
	gtk_widget_class_bind_template_child(widget_class, PidginScheduler,
	                                     sorter);

	gtk_widget_class_bind_template_callback(widget_class,
	                                        pidgin_scheduler_items_changed);
	gtk_widget_class_bind_template_callback(widget_class,
	                                        pidgin_scheduler_position_to_variant);
	gtk_widget_class_bind_template_callback(widget_class,
	                                        pidgin_scheduler_search_changed);
	gtk_widget_class_bind_template_callback(widget_class,
	                                        pidgin_scheduler_task_state_changed);
}

/******************************************************************************
 * Public API
 *****************************************************************************/
PurpleScheduler *
pidgin_scheduler_get_scheduler(PidginScheduler *scheduler) {
	g_return_val_if_fail(PIDGIN_IS_SCHEDULER(scheduler), NULL);

	return scheduler->scheduler;
}

GtkWidget *
pidgin_scheduler_new(PurpleScheduler *scheduler) {
	g_return_val_if_fail(PURPLE_IS_SCHEDULER(scheduler), NULL);

	return g_object_new(PIDGIN_TYPE_SCHEDULER,
	                    "scheduler", scheduler,
	                    NULL);
}
