/*
 * Online accounts: signing in to services on the web once, here, for the
 * apps that work with them (News with rssnail, say). The accounts and
 * their tokens belong to c8-accounts (org.cont8nuum.Accounts1, in
 * c8-protocols); this page only shows them and asks it for changes.
 *
 * Signing in happens in the browser: c8-accounts gives us the address
 * and we open it, so the browser comes forward with our activation
 * token. Until it says how it went, the page shows a band with Cancel.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "settings.h"

#define BUS_NAME "org.cont8nuum.Accounts"
#define OBJ_PATH "/org/cont8nuum/Accounts"
#define IFACE "org.cont8nuum.Accounts1"
#define BADGE 48

static struct {
	GDBusConnection *bus;
	guint changed_sub, finished_sub;
	GVariant *providers, *accounts; // aa{sv}, as last read
	bool unavailable; // no c8-accounts
	char *handle, *uri; // a sign-in going on
	char *signing_in; // its provider's name
	bool paste; // waiting for the address the browser ended on
	guint next_sub;
	struct c8ui_widget *page, *list, *add, *band, *band_text;
	struct c8ui_widget *paste_row, *paste_entry;
} acc;

static void reload(void);
static void rebuild(void);

static const char *dict_str(GVariant *dict, const char *key) {
	const char *s = NULL;
	if (dict == NULL || !g_variant_lookup(dict, key, "&s", &s)) {
		return "";
	}
	return s;
}

/* An account's address as shown: the persona's in stealth mode */
static const char *shown_email(const char *email) {
	return email[0] && c8_stealth() ? c8_stealth_email() : email;
}

static bool dict_bool(GVariant *dict, const char *key) {
	gboolean b = FALSE;
	return dict && g_variant_lookup(dict, key, "b", &b) && b;
}

/* Errors, without D-Bus's prefix; quiet for a cancelled sign-in */
static void call_failed(const char *title, GError *error) {
	g_dbus_error_strip_remote_error(error);
	show_error(title, error->message);
}

/* The badge: the provider's logo, or its colour with its first letter,
 * as a tile */

struct badge {
	uint32_t color;
	char letter[8];
	struct c8ui_icon *logo;
};

static void badge_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct badge *b = w->user_data;
	if (b->logo) {
		c8ui_icon_draw_fit(cr, b->logo, w->rect.x + BADGE / 2.0,
			w->rect.y + BADGE / 2.0, BADGE);
		return;
	}
	c8ui_set_source(cr, b->color, 1);
	cairo_rectangle(cr, w->rect.x, w->rect.y, BADGE, BADGE);
	cairo_fill(cr);
	const char *family = c8ui_root_theme(w->root)->font;
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_SUBHEADER);
	double tw, th;
	c8ui_text_size(family, font, b->letter, 0, 1, &tw, &th);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, font, b->letter, w->rect.x + (BADGE - tw) / 2,
		w->rect.y + (BADGE - th) / 2, 0, 1);
}

static void badge_gone(struct c8ui_widget *w, void *data) {
	struct badge *b = w->user_data;
	if (b->logo) {
		c8ui_icon_destroy(b->logo);
	}
	g_free(b);
}

static struct c8ui_widget *badge_new(const char *color, const char *icon,
		const char *name) {
	struct badge *b = g_new0(struct badge, 1);
	if (icon[0]) {
		b->logo = c8ui_icon_load(NULL, icon);
	}
	b->color = 0x4a5c2f;
	if (color[0]) {
		c8ui_parse_color(color, &b->color);
	}
	gunichar c = g_utf8_get_char_validated(name, -1);
	if (c == (gunichar)-1 || c == (gunichar)-2 || c == 0) {
		c = '?';
	}
	g_unichar_to_utf8(g_unichar_toupper(c), b->letter);
	struct c8ui_widget *w = c8ui_canvas_new(BADGE, BADGE, badge_draw, NULL,
		NULL);
	w->user_data = b;
	w->on_destroy = badge_gone;
	w->align = C8UI_ALIGN_START;
	return w;
}

/* A badge with two lines beside it */
static struct c8ui_widget *heading_row(const char *color, const char *icon,
		const char *badge, const char *title, const char *subtitle) {
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 16);
	add(row, badge_new(color, icon, badge));
	struct c8ui_widget *text = c8ui_box_new(C8UI_VERTICAL, 2);
	text->expand = true;
	text->align = C8UI_ALIGN_CENTER;
	add(text, c8ui_label_new(title, C8UI_TEXT_ITEM));
	if (subtitle && subtitle[0]) {
		add(text, caption(subtitle));
	}
	add(row, text);
	return row;
}

/* Strings that go with a widget, freed with it */
static void strings_gone(struct c8ui_widget *w, void *data) {
	g_strfreev(w->user_data);
}

static void keep_strings(struct c8ui_widget *w, const char *a, const char *b) {
	const char *v[] = { a, b, NULL };
	w->user_data = g_strdupv((char **)v);
	w->on_destroy = strings_gone;
}

/* Signing in */

static void open_uri(void) {
	if (acc.uri) {
		c8ui_window_open_uri(app.window, acc.uri);
	}
}

static void sign_in_over(void) {
	g_clear_pointer(&acc.handle, g_free);
	g_clear_pointer(&acc.uri, g_free);
	g_clear_pointer(&acc.signing_in, g_free);
	acc.paste = false;
	if (acc.finished_sub) {
		g_dbus_connection_signal_unsubscribe(acc.bus, acc.finished_sub);
		acc.finished_sub = 0;
	}
	if (acc.next_sub) {
		g_dbus_connection_signal_unsubscribe(acc.bus, acc.next_sub);
		acc.next_sub = 0;
	}
	if (acc.paste_entry) {
		c8ui_entry_set(acc.paste_entry, "");
	}
	rebuild();
}

/* On to the next service of the sign-in. After a paste the browser isn't
 * coming back by itself: open its page */
static void next_step(GDBusConnection *c, const char *sender, const char *path,
		const char *iface, const char *signal, GVariant *params,
		gpointer data) {
	const char *handle, *uri;
	gboolean paste;
	g_variant_get(params, "(&s&sb)", &handle, &uri, &paste);
	if (acc.handle == NULL || strcmp(handle, acc.handle) != 0) {
		return;
	}
	bool was_paste = acc.paste;
	g_free(acc.uri);
	acc.uri = g_strdup(uri);
	acc.paste = paste;
	if (was_paste) {
		open_uri();
	}
	if (acc.paste_entry) {
		c8ui_entry_set(acc.paste_entry, "");
	}
	rebuild();
}

static void pasted(GObject *source, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r) {
		g_variant_unref(r);
		return; // SignInNext or SignInFinished says what's next
	}
	call_failed("That address didn't work", error);
	g_error_free(error);
}

static void continue_clicked(struct c8ui_widget *w, void *data) {
	const char *text = acc.paste_entry ? c8ui_entry_get(acc.paste_entry) : "";
	if (acc.handle == NULL || !acc.paste || !text[0]) {
		return;
	}
	g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE, "FinishSignIn",
		g_variant_new("(ss)", acc.handle, text), NULL, G_DBUS_CALL_FLAGS_NONE,
		30000, NULL, pasted, NULL);
}

static void finished(GDBusConnection *c, const char *sender, const char *path,
		const char *iface, const char *signal, GVariant *params,
		gpointer data) {
	const char *handle, *account, *error;
	g_variant_get(params, "(&s&s&s)", &handle, &account, &error);
	if (acc.handle == NULL || strcmp(handle, acc.handle) != 0) {
		return;
	}
	char *why = error[0] && strcmp(error, "cancelled") != 0 ?
		g_strdup(error) : NULL;
	sign_in_over();
	reload();
	if (why) {
		show_error("Couldn't sign in", why);
		g_free(why);
	}
}

static void signed_in_started(GObject *source, GAsyncResult *res,
		gpointer data) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r == NULL) {
		sign_in_over();
		call_failed("Couldn't sign in", error);
		g_error_free(error);
		return;
	}
	gboolean paste;
	g_variant_get(r, "(ssb)", &acc.handle, &acc.uri, &paste);
	acc.paste = paste;
	g_variant_unref(r);
	open_uri();
	rebuild();
}

/* account "" for a new one; service NULL for all of them */
static void sign_in(const char *provider, const char *provider_name,
		const char *account, const char *service) {
	if (acc.bus == NULL || acc.signing_in) {
		return;
	}
	acc.signing_in = g_strdup(provider_name);
	acc.finished_sub = g_dbus_connection_signal_subscribe(acc.bus, NULL,
		IFACE, "SignInFinished", OBJ_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
		finished, NULL, NULL);
	acc.next_sub = g_dbus_connection_signal_subscribe(acc.bus, NULL,
		IFACE, "SignInNext", OBJ_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
		next_step, NULL, NULL);
	const char *one[] = { service, NULL };
	g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE, "SignIn",
		g_variant_new("(ss^as)", provider, account, service ? one :
		(const char *[]){ NULL }), G_VARIANT_TYPE("(ssb)"),
		G_DBUS_CALL_FLAGS_NONE, 60000, NULL, signed_in_started, NULL);
	rebuild();
}

static void cancel_clicked(struct c8ui_widget *w, void *data) {
	if (acc.handle) {
		g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE,
			"CancelSignIn", g_variant_new("(s)", acc.handle), NULL,
			G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
	}
	sign_in_over();
}

static void again_clicked(struct c8ui_widget *w, void *data) {
	open_uri();
}

/* Changing things */

static void called(GObject *source, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r) {
		g_variant_unref(r);
	} else {
		call_failed(data, error);
		g_error_free(error);
		reload();
	}
}

static void service_toggled(struct c8ui_widget *w, void *data) {
	char **ids = w->user_data;
	g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE,
		"SetServiceEnabled", g_variant_new("(ssb)", ids[0], ids[1],
		c8ui_toggle_get(w)), NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, called,
		"Couldn't change that");
}

static GVariant *account_by_id(const char *id) {
	GVariantIter it;
	GVariant *a;
	if (acc.accounts == NULL) {
		return NULL;
	}
	g_variant_iter_init(&it, acc.accounts);
	while ((a = g_variant_iter_next_value(&it))) {
		if (strcmp(dict_str(a, "id"), id) == 0) {
			return a;
		}
		g_variant_unref(a);
	}
	return NULL;
}

static void sign_in_again_clicked(struct c8ui_widget *w, void *data) {
	char **ids = w->user_data;
	GVariant *a = account_by_id(ids[0]);
	if (a) {
		sign_in(dict_str(a, "provider"), dict_str(a, "provider-name"), ids[0],
			ids[1][0] ? ids[1] : NULL);
		g_variant_unref(a);
	}
}

static void remove_answered(int choice, void *data) {
	char *id = data;
	if (choice == 0) {
		g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE,
			"RemoveAccount", g_variant_new("(s)", id), NULL,
			G_DBUS_CALL_FLAGS_NONE, -1, NULL, called,
			"Couldn't remove the account");
	}
	g_free(id);
}

static void remove_clicked(struct c8ui_widget *w, void *data) {
	char **ids = w->user_data;
	GVariant *a = account_by_id(ids[0]);
	if (a == NULL) {
		return;
	}
	char *text = g_strdup_printf("Apps on this PC won't use %s's %s any "
		"more, and you'll be signed out of it here. The account itself "
		"stays as it is online.", dict_str(a, "provider-name"),
		dict_str(a, "email")[0] ? shown_email(dict_str(a, "email")) :
		"account");
	static const char *const buttons[] = { "Remove", "Cancel" };
	c8ui_dialog_show(app.root, "Remove this account?", text, buttons, 2,
		remove_answered, g_strdup(ids[0]));
	g_free(text);
	g_variant_unref(a);
}

static void provider_invoked(struct c8ui_widget *w, void *data) {
	char **ids = w->user_data;
	sign_in(ids[0], ids[1], "", NULL);
}

/* Showing it */

static struct c8ui_widget *service_row(const char *account, GVariant *s) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 6);
	if (!dict_bool(s, "ready")) {
		/* Listed so it's known, but it can't be signed in to yet */
		add(box, c8ui_label_new(dict_str(s, "name"), C8UI_TEXT_BODY));
		add(box, caption("Not available yet"));
		return box;
	}
	bool again = dict_bool(s, "needs-sign-in");
	struct c8ui_widget *t = c8ui_toggle_new(dict_str(s, "name"),
		dict_str(s, "description"), dict_bool(s, "enabled"), service_toggled,
		NULL);
	keep_strings(t, account, dict_str(s, "id"));
	add(box, t);
	if (again) {
		struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
		c8ui_box_set_narrow_orientation(row, C8UI_VERTICAL);
		struct c8ui_widget *why = caption(dict_bool(s, "signed-in") ?
			"Sign in again so apps can use this." :
			"Sign in to let apps use this.");
		why->align = C8UI_ALIGN_CENTER;
		add(row, why);
		struct c8ui_widget *b = c8ui_button_new("Sign in",
			sign_in_again_clicked, NULL);
		keep_strings(b, account, dict_str(s, "id"));
		c8ui_widget_set_disabled(b, acc.signing_in != NULL);
		add(row, b);
		add(box, row);
	}
	return box;
}

static struct c8ui_widget *account_block(GVariant *a) {
	struct c8ui_widget *block = c8ui_box_new(C8UI_VERTICAL, 16);
	block->fill = true;
	const char *id = dict_str(a, "id");
	const char *email = shown_email(dict_str(a, "email"));
	char *sub = g_strdup_printf(email[0] ? "%s · %s" : "%s",
		dict_str(a, "provider-name"), email);
	const char *name = dict_str(a, "name");
	add(block, heading_row(dict_str(a, "color"), dict_str(a, "icon"),
		dict_str(a, "provider-name"),
		name[0] && c8_stealth() ? c8_stealth_name() : name, sub));
	g_free(sub);

	struct c8ui_widget *services = c8ui_box_new(C8UI_VERTICAL, 14);
	c8ui_box_set_padding(services, BADGE + 16, 0, 0, 0);
	c8ui_box_set_narrow_padding(services, 0, 0, 0, 0);
	GVariant *list = g_variant_lookup_value(a, "services",
		G_VARIANT_TYPE("aa{sv}"));
	GVariantIter it;
	GVariant *s;
	if (list) {
		g_variant_iter_init(&it, list);
		while ((s = g_variant_iter_next_value(&it))) {
			add(services, service_row(id, s));
			g_variant_unref(s);
		}
		g_variant_unref(list);
	}
	struct c8ui_widget *remove = c8ui_button_new("Remove", remove_clicked, NULL);
	keep_strings(remove, id, "");
	remove->align = C8UI_ALIGN_START;
	add(services, remove);
	add(block, services);
	return block;
}

static struct c8ui_widget *provider_item(GVariant *p) {
	const char *name = dict_str(p, "name");
	struct c8ui_widget *row = heading_row(dict_str(p, "color"),
		dict_str(p, "icon"), name, name, dict_str(p, "description"));
	c8ui_box_set_padding(row, 0, 8, 8, 8);
	struct c8ui_widget *item = c8ui_item_container_new(row);
	c8ui_item_container_set_selectable(item, false);
	c8ui_item_container_set_tap(item, C8UI_ITEM_TAP_INVOKE);
	c8ui_item_container_on_invoke(item, provider_invoked, NULL);
	keep_strings(item, dict_str(p, "id"), name);
	item->fill = true;
	c8ui_widget_set_disabled(item, acc.signing_in != NULL);
	return item;
}

static void rebuild(void) {
	if (acc.page == NULL) {
		return;
	}
	c8ui_widget_clear(acc.list);
	c8ui_widget_clear(acc.add);

	acc.band->hidden = acc.signing_in == NULL;
	acc.paste_row->hidden = !acc.paste;
	if (acc.signing_in) {
		/* Pasting: the page they end on can't send us back by itself
		 * (an empty page, or an error) */
		char *text = g_strdup_printf(acc.paste ? "Sign in to %s in your "
			"browser. When it's done it shows an empty page or an error: "
			"copy the whole address from the address bar and paste it here." :
			acc.uri ? "Finish signing in to %s in your browser, then come "
			"back here." : "Getting ready to sign in to %s…", acc.signing_in);
		c8ui_label_set_text(acc.band_text, text);
		g_free(text);
	}

	if (acc.unavailable) {
		add(acc.list, caption("Online accounts aren't available: c8-accounts "
			"isn't installed, or didn't start."));
		c8ui_widget_queue_layout(acc.page);
		return;
	}
	int n = 0;
	if (acc.accounts) {
		GVariantIter it;
		GVariant *a;
		g_variant_iter_init(&it, acc.accounts);
		while ((a = g_variant_iter_next_value(&it))) {
			add(acc.list, account_block(a));
			g_variant_unref(a);
			n++;
		}
	}
	if (n == 0) {
		add(acc.list, caption(acc.accounts ? "You haven't added an account "
			"yet." : "Looking…"));
	}
	if (acc.providers) {
		GVariantIter it;
		GVariant *p;
		g_variant_iter_init(&it, acc.providers);
		while ((p = g_variant_iter_next_value(&it))) {
			add(acc.add, provider_item(p));
			g_variant_unref(p);
		}
	}
	c8ui_widget_queue_layout(acc.page);
}

/* Reading it */

static void got_list(GObject *source, GAsyncResult *res, gpointer data) {
	GVariant **slot = data;
	GError *error = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&error);
	if (r == NULL) {
		if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
			g_warning("accounts: %s", error->message);
			acc.unavailable = true;
		}
		g_error_free(error);
		rebuild();
		return;
	}
	acc.unavailable = false;
	if (*slot) {
		g_variant_unref(*slot);
	}
	*slot = g_variant_get_child_value(r, 0);
	g_variant_unref(r);
	rebuild();
}

static void reload(void) {
	if (acc.bus == NULL) {
		return;
	}
	g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE, "ListAccounts",
		NULL, G_VARIANT_TYPE("(aa{sv})"), G_DBUS_CALL_FLAGS_NONE, 10000, NULL,
		got_list, &acc.accounts);
	if (acc.providers == NULL) {
		g_dbus_connection_call(acc.bus, BUS_NAME, OBJ_PATH, IFACE,
			"ListProviders", NULL, G_VARIANT_TYPE("(aa{sv})"),
			G_DBUS_CALL_FLAGS_NONE, 10000, NULL, got_list, &acc.providers);
	}
}

static void changed(GDBusConnection *c, const char *sender, const char *path,
		const char *iface, const char *signal, GVariant *params,
		gpointer data) {
	reload();
}

/* The page */

static void page_gone(struct c8ui_widget *w, void *data) {
	if (acc.page != w) {
		return;
	}
	acc.page = acc.list = acc.add = acc.band = acc.band_text = NULL;
	acc.paste_row = acc.paste_entry = NULL;
	if (acc.changed_sub) {
		g_dbus_connection_signal_unsubscribe(acc.bus, acc.changed_sub);
		acc.changed_sub = 0;
	}
	/* A sign-in going on carries on: its end is still listened for */
}

static void accounts_build(struct c8ui_widget *box) {
	if (acc.bus == NULL) {
		acc.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
		acc.unavailable = acc.bus == NULL;
	}
	acc.page = c8ui_box_new(C8UI_VERTICAL, 18);
	acc.page->fill = true;
	acc.page->on_destroy = page_gone;
	add(box, acc.page);

	add(acc.page, caption("Sign in to your accounts on the web here, once, "
		"and the apps that work with them use them. Passwords stay with the "
		"site; this PC keeps only what lets it in, in your wallet."));

	/* While signing in: what to do, and a way out */
	acc.band = c8ui_box_new(C8UI_VERTICAL, 10);
	acc.band->fill = true;
	c8ui_box_set_padding(acc.band, 16, 14, 16, 16);
	c8ui_widget_set_background(acc.band, 0xf2f2f2);
	struct c8ui_widget *top = c8ui_box_new(C8UI_HORIZONTAL, 14);
	struct c8ui_widget *ring = c8ui_ring_new(0);
	c8ui_ring_set_active(ring, true);
	ring->align = C8UI_ALIGN_CENTER;
	add(top, ring);
	acc.band_text = c8ui_label_new("", C8UI_TEXT_BODY);
	acc.band_text->expand = true;
	acc.band_text->align = C8UI_ALIGN_CENTER;
	add(top, acc.band_text);
	add(acc.band, top);
	acc.paste_row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_narrow_orientation(acc.paste_row, C8UI_VERTICAL);
	acc.paste_row->fill = true;
	acc.paste_entry = c8ui_entry_new(NULL, "", continue_clicked, NULL);
	/* Enter in the box; not leaving it */
	c8ui_entry_set_enter_only(acc.paste_entry, true);
	c8ui_entry_set_placeholder(acc.paste_entry, "https://…?code=…");
	acc.paste_entry->expand = true;
	acc.paste_entry->fill = true;
	add(acc.paste_row, acc.paste_entry);
	struct c8ui_widget *go = c8ui_button_new("Continue", continue_clicked, NULL);
	c8ui_button_set_primary(go, true);
	add(acc.paste_row, go);
	add(acc.band, acc.paste_row);
	struct c8ui_widget *buttons = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(buttons, true);
	add(buttons, c8ui_button_new("Open the page again", again_clicked, NULL));
	add(buttons, c8ui_button_new("Cancel", cancel_clicked, NULL));
	add(acc.band, buttons);
	add(acc.page, acc.band);

	add(acc.page, section_title("Your accounts"));
	acc.list = c8ui_box_new(C8UI_VERTICAL, 30);
	acc.list->fill = true;
	add(acc.page, acc.list);

	add(acc.page, section_title("Add an account"));
	acc.add = c8ui_box_new(C8UI_VERTICAL, 4);
	acc.add->fill = true;
	add(acc.page, acc.add);

	if (acc.bus && acc.changed_sub == 0) {
		acc.changed_sub = g_dbus_connection_signal_subscribe(acc.bus, NULL,
			IFACE, "Changed", OBJ_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE, changed,
			NULL, NULL);
	}
	rebuild();
	reload();
}

const struct page page_accounts = {
	.name = "accounts",
	.title = "Online accounts",
	.build = accounts_build,
};
