/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
 * vi:set noexpandtab tabstop=8 shiftwidth=8:
 *
 * Copyright (C) 2013-2016 Richard Hughes <richard@hughsie.com>
 * Copyright (C) 2014-2018 Kalev Lember <klember@redhat.com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "config.h"

#include <glib/gi18n.h>

#include "gs-installed-updates-dialog.h"
#include "gs-app-details-page.h"
#include "gs-app-row.h"
#include "gs-os-update-page.h"
#include "gs-update-list.h"
#include "gs-common.h"

struct _GsInstalledUpdatesDialog
{
	AdwDialog	 parent_instance;

	GCancellable	*cancellable;
	GsPluginLoader	*plugin_loader;
	GtkWidget	*navigation_view;
	GtkWidget	*list_box_installed_updates;
	GtkWidget	*spinner;
	GtkWidget	*stack;
	AdwWindowTitle	*window_title;
	AdwNavigationPage	*default_page;
};

G_DEFINE_TYPE (GsInstalledUpdatesDialog, gs_installed_updates_dialog, ADW_TYPE_DIALOG)

typedef enum {
	PROP_PLUGIN_LOADER = 1,
} GsInstalledUpdatesDialogProperty;

static GParamSpec *obj_props[PROP_PLUGIN_LOADER + 1]  = { NULL, };

static void gs_installed_updates_dialog_show_update_details (GsInstalledUpdatesDialog *dialog, GsApp *app);

static void
installed_updates_row_activated_cb (GsUpdateList *update_list,
				    GsApp *app,
				    GsInstalledUpdatesDialog *dialog)
{
	gs_installed_updates_dialog_show_update_details (dialog, app);
}

static void
get_installed_updates_cb (GsPluginLoader *plugin_loader,
                          GAsyncResult *res,
                          GsInstalledUpdatesDialog *dialog)
{
	guint i;
	guint64 install_date;
	g_autoptr(GsPluginJobListApps) list_apps_job = NULL;
	GsAppList *list;
	g_autoptr(GError) error = NULL;

	/* get the results */
	gs_plugin_loader_job_process_finish (plugin_loader, res, (GsPluginJob **) &list_apps_job, &error);

	/* if we're in teardown, short-circuit and return immediately without
	 * dereferencing priv variables */
	if (g_error_matches (error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_CANCELLED) ||
	    g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) ||
	    dialog->spinner == NULL) {
		g_debug ("get installed updates cancelled");
		return;
	}

	/* error */
	if (error != NULL) {
		g_warning ("failed to get installed updates: %s", error->message);
		gtk_stack_set_visible_child_name (GTK_STACK (dialog->stack), "empty");
		return;
	}

	list = gs_plugin_job_list_apps_get_result_list (list_apps_job);

	/* no results */
	if (gs_app_list_length (list) == 0) {
		g_debug ("no installed updates to show");
		gtk_stack_set_visible_child_name (GTK_STACK (dialog->stack), "empty");
		return;
	}

	/* set the header title using the latest app install date */
	install_date = 0;
	for (i = 0; i < gs_app_list_length (list); i++) {
		GsApp *app = gs_app_list_index (list, i);
		guint64 app_inst_date = gs_app_get_install_date (app);
		if (app_inst_date > install_date)
			install_date = app_inst_date;

		/* handle also "System Updates" */
		if (gs_app_has_quirk (app, GS_APP_QUIRK_IS_PROXY)) {
			GsAppList *related = gs_app_get_related (app);
			for (guint j = 0; j < gs_app_list_length (related); j++) {
				GsApp *rel_app = gs_app_list_index (related, j);
				app_inst_date = gs_app_get_install_date (rel_app);
				if (app_inst_date > install_date)
					install_date = app_inst_date;
			}
		}
	}
	if (install_date > 0) {
		g_autoptr(GDateTime) date = NULL;
		g_autofree gchar *date_str = NULL;
		g_autofree gchar *subtitle = NULL;

		date = g_date_time_new_from_unix_utc ((gint64) install_date);
		date_str = g_date_time_format (date, "%x");

		/* TRANSLATORS: this is the subtitle of the installed updates dialog window.
		   %s will be replaced by the date when the updates were installed.
		   The date format is defined by the locale's preferred date representation
		   ("%x" in strftime.) */
		subtitle = g_strdup_printf (_("Installed on %s"), date_str);
		adw_window_title_set_subtitle (dialog->window_title, subtitle);
	}

	gtk_stack_set_visible_child_name (GTK_STACK (dialog->stack), "installed-updates-list");

	gs_update_list_remove_all (GS_UPDATE_LIST (dialog->list_box_installed_updates));
	for (i = 0; i < gs_app_list_length (list); i++) {
		gs_update_list_add_app (GS_UPDATE_LIST (dialog->list_box_installed_updates),
					gs_app_list_index (list, i));
	}
}

static void
gs_installed_updates_dialog_map (GtkWidget *widget)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (widget);
	g_autoptr(GsAppQuery) query = NULL;
	g_autoptr(GsPluginJob) plugin_job = NULL;

	GTK_WIDGET_CLASS (gs_installed_updates_dialog_parent_class)->map (widget);

	gtk_stack_set_visible_child_name (GTK_STACK (dialog->stack), "spinner");

	query = gs_app_query_new ("is-historical-update", GS_APP_QUERY_TRISTATE_TRUE,
				  "refine-flags", GS_PLUGIN_REFINE_FLAGS_DISABLE_FILTERING,
				  "refine-require-flags", GS_PLUGIN_REFINE_REQUIRE_FLAGS_UPDATE_SEVERITY |
							  GS_PLUGIN_REFINE_REQUIRE_FLAGS_ICON |
							  GS_PLUGIN_REFINE_REQUIRE_FLAGS_VERSION,
				  NULL);
	plugin_job = gs_plugin_job_list_apps_new (query, GS_PLUGIN_LIST_APPS_FLAGS_INTERACTIVE);
	gs_plugin_loader_job_process_async (dialog->plugin_loader, plugin_job,
	                                    dialog->cancellable,
	                                    (GAsyncReadyCallback) get_installed_updates_cb,
	                                    dialog);
}

static void
gs_installed_updates_dialog_unmap (GtkWidget *widget)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (widget);

	g_cancellable_cancel (dialog->cancellable);

	GTK_WIDGET_CLASS (gs_installed_updates_dialog_parent_class)->unmap (widget);
}

static void
app_activated_cb (GtkWidget *widget, GsApp *app, GsInstalledUpdatesDialog *page)
{
	gs_installed_updates_dialog_show_update_details (page, app);
}

static void
gs_installed_updates_dialog_show_update_details (GsInstalledUpdatesDialog *dialog, GsApp *app)
{
	GtkWidget *page;
	AsComponentKind kind;
	g_autofree gchar *str = NULL;

	/* debug */
	str = gs_app_to_string (app);
	g_debug ("%s", str);

	/* set update description */
	kind = gs_app_get_kind (app);
	if (kind == AS_COMPONENT_KIND_GENERIC &&
	    gs_app_get_special_kind (app) == GS_APP_SPECIAL_KIND_OS_UPDATE) {
		page = gs_os_update_page_new ();
		gs_os_update_page_set_app (GS_OS_UPDATE_PAGE (page), app);
		g_signal_connect (page, "app-activated",
				  G_CALLBACK (app_activated_cb), dialog);
	} else {
		page = gs_app_details_page_new (dialog->plugin_loader);
		gs_app_details_page_set_app (GS_APP_DETAILS_PAGE (page), app);
	}

	adw_navigation_view_push (ADW_NAVIGATION_VIEW (dialog->navigation_view), ADW_NAVIGATION_PAGE (page));
}

static void
gs_installed_updates_dialog_get_property (GObject    *object,
                                          guint       prop_id,
                                          GValue     *value,
                                          GParamSpec *pspec)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (object);

	switch ((GsInstalledUpdatesDialogProperty) prop_id) {
	case PROP_PLUGIN_LOADER:
		g_value_set_object (value, dialog->plugin_loader);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
gs_installed_updates_dialog_set_property (GObject      *object,
                                          guint         prop_id,
                                          const GValue *value,
                                          GParamSpec   *pspec)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (object);

	switch ((GsInstalledUpdatesDialogProperty) prop_id) {
	case PROP_PLUGIN_LOADER:
		/* Construct only: */
		g_assert (dialog->plugin_loader == NULL);
		dialog->plugin_loader = g_value_dup_object (value);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
gs_installed_updates_dialog_constructed (GObject *object)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (object);

	g_assert (dialog->plugin_loader != NULL);

	G_OBJECT_CLASS (gs_installed_updates_dialog_parent_class)->constructed (object);
}

static void
gs_installed_updates_dialog_dispose (GObject *object)
{
	GsInstalledUpdatesDialog *dialog = GS_INSTALLED_UPDATES_DIALOG (object);

	g_cancellable_cancel (dialog->cancellable);
	g_clear_object (&dialog->cancellable);

	g_clear_object (&dialog->plugin_loader);

	G_OBJECT_CLASS (gs_installed_updates_dialog_parent_class)->dispose (object);
}

static void
gs_installed_updates_dialog_init (GsInstalledUpdatesDialog *dialog)
{
	g_type_ensure (GS_TYPE_UPDATE_LIST);

	gtk_widget_init_template (GTK_WIDGET (dialog));

	dialog->cancellable = g_cancellable_new ();

	g_signal_connect (dialog->list_box_installed_updates, "show-update",
			  G_CALLBACK (installed_updates_row_activated_cb), dialog);
}

static void
gs_installed_updates_dialog_class_init (GsInstalledUpdatesDialogClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);

	object_class->get_property = gs_installed_updates_dialog_get_property;
	object_class->set_property = gs_installed_updates_dialog_set_property;
	object_class->constructed = gs_installed_updates_dialog_constructed;
	object_class->dispose = gs_installed_updates_dialog_dispose;

	widget_class->map = gs_installed_updates_dialog_map;
	widget_class->unmap = gs_installed_updates_dialog_unmap;

	/**
	 * GsInstalledUpdatesDialog:plugin-loader
	 *
	 * The plugin loader of the dialog.
	 *
	 * Since: 50
	 */
	obj_props[PROP_PLUGIN_LOADER] =
		g_param_spec_object ("plugin-loader", NULL, NULL,
				     GS_TYPE_PLUGIN_LOADER,
				     G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties (object_class, G_N_ELEMENTS (obj_props), obj_props);

	gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/Software/gs-installed-updates-dialog.ui");

	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, navigation_view);
	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, list_box_installed_updates);
	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, spinner);
	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, stack);
	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, window_title);
	gtk_widget_class_bind_template_child (widget_class, GsInstalledUpdatesDialog, default_page);
}

GsInstalledUpdatesDialog *
gs_installed_updates_dialog_new (GsPluginLoader *plugin_loader)
{
	return g_object_new (GS_TYPE_INSTALLED_UPDATES_DIALOG,
			     "plugin-loader", plugin_loader,
			     NULL);
}
