/*
 * Mounting network places (and anything else gvfs mounts on demand):
 * GIO's questions, a password or which of a few choices, are asked in
 * dialogs over the window.
 */
#include <string.h>
#include "files.h"
#include "stealth.h"

struct mount {
	struct c8ui_root *root;
	GFile *location;
	GMountOperation *op;
	struct c8ui_widget *dialog;
	struct c8ui_widget *user, *domain, *password, *remember, *guest;
	GAskPasswordFlags flags;
	bool answered; // the dialog's question was answered (or given up)
	mounted_fn done;
	void *data;
};

static GList *mounts; // struct mount: under way

void mount_forget_root(struct c8ui_root *root) {
	for (GList *l = mounts; l; l = l->next) {
		struct mount *m = l->data;
		if (m->root == root) {
			m->root = NULL; // no window to ask in any more
		}
	}
}

/* A dialog going without an answer (its window closed): give up */
static void dialog_gone(struct c8ui_widget *w, void *data) {
	struct mount *m = data;
	m->dialog = NULL;
	if (!m->answered) {
		m->answered = true;
		g_mount_operation_reply(m->op, G_MOUNT_OPERATION_ABORTED);
	}
}

static struct c8ui_widget *ask(struct mount *m, const char *title,
		const char *message, const char *const *buttons, int count,
		c8ui_dialog_fn fn) {
	m->answered = false;
	/* GIO's questions name the user and the server */
	char *shown = c8_stealth_text(message);
	struct c8ui_widget *d = c8ui_dialog_show(m->root, title, shown, buttons,
		count, fn, m);
	g_free(shown);
	d->on_destroy = dialog_gone;
	m->dialog = d;
	return d;
}

/* Passwords */

static void password_answered(int choice, void *data) {
	struct mount *m = data;
	if (m->answered) {
		return;
	}
	m->answered = true;
	if (choice != 0) {
		g_mount_operation_reply(m->op, G_MOUNT_OPERATION_ABORTED);
		return;
	}
	bool guest = m->guest && c8ui_checkbox_get(m->guest);
	if (guest) {
		g_mount_operation_set_anonymous(m->op, TRUE);
	} else {
		if (m->user) {
			g_mount_operation_set_username(m->op, c8ui_entry_get(m->user));
		}
		if (m->domain) {
			g_mount_operation_set_domain(m->op, c8ui_entry_get(m->domain));
		}
		g_mount_operation_set_password(m->op, c8ui_entry_get(m->password));
		g_mount_operation_set_password_save(m->op,
			m->remember && c8ui_checkbox_get(m->remember) ?
			G_PASSWORD_SAVE_PERMANENTLY : G_PASSWORD_SAVE_NEVER);
	}
	g_mount_operation_reply(m->op, G_MOUNT_OPERATION_HANDLED);
}

static void entered(struct c8ui_widget *entry, void *data) {
	struct mount *m = data;
	if (m->dialog) {
		c8ui_dialog_choose(m->dialog, 0);
	}
}

static void ask_password(GMountOperation *op, const char *message,
		const char *user, const char *domain, GAskPasswordFlags flags,
		gpointer data) {
	struct mount *m = data;
	static const char *const buttons[] = { "Connect", "Cancel" };
	/* GMountOperation's own handler would answer "unhandled" from an idle
	 * before the dialog is: this one answers */
	g_signal_stop_emission_by_name(op, "ask-password");
	if (m->root == NULL) {
		g_mount_operation_reply(op, G_MOUNT_OPERATION_ABORTED);
		return;
	}
	struct c8ui_widget *d = ask(m, "Sign in", message, buttons, 2,
		password_answered);
	m->flags = flags;
	m->user = m->domain = m->password = m->remember = m->guest = NULL;
	struct c8ui_widget *first = NULL;
	if (flags & G_ASK_PASSWORD_NEED_USERNAME) {
		m->user = c8ui_entry_new("User name", user ? user : "", entered, m);
		c8ui_dialog_add(d, m->user);
		first = m->user;
	}
	if (flags & G_ASK_PASSWORD_NEED_DOMAIN) {
		m->domain = c8ui_entry_new("Domain", domain ? domain : "", entered, m);
		c8ui_dialog_add(d, m->domain);
		first = first ? first : m->domain;
	}
	m->password = c8ui_entry_new("Password", "", entered, m);
	c8ui_entry_set_password(m->password, true);
	c8ui_dialog_add(d, m->password);
	if (!(flags & G_ASK_PASSWORD_NEED_PASSWORD)) {
		m->password->hidden = true;
	}
	if (flags & G_ASK_PASSWORD_SAVING_SUPPORTED) {
		m->remember = c8ui_checkbox_new("Remember my password", false, NULL,
			NULL);
		c8ui_dialog_add(d, m->remember);
	}
	if (flags & G_ASK_PASSWORD_ANONYMOUS_SUPPORTED) {
		m->guest = c8ui_checkbox_new("Connect as a guest", false, NULL, NULL);
		c8ui_dialog_add(d, m->guest);
	}
	/* Straight to what has to be typed */
	if (first && c8ui_entry_get(first)[0] == '\0') {
		c8ui_widget_grab_focus(first);
	} else if (!m->password->hidden) {
		c8ui_widget_grab_focus(m->password);
	}
}

/* Questions: a certificate that isn't known, say */

static void question_answered(int choice, void *data) {
	struct mount *m = data;
	if (m->answered) {
		return;
	}
	m->answered = true;
	if (choice < 0) {
		g_mount_operation_reply(m->op, G_MOUNT_OPERATION_ABORTED);
		return;
	}
	g_mount_operation_set_choice(m->op, choice);
	g_mount_operation_reply(m->op, G_MOUNT_OPERATION_HANDLED);
}

static void ask_question(GMountOperation *op, const char *message,
		const char **choices, gpointer data) {
	struct mount *m = data;
	g_signal_stop_emission_by_name(op, "ask-question"); // as for passwords
	if (m->root == NULL) {
		g_mount_operation_reply(op, G_MOUNT_OPERATION_ABORTED);
		return;
	}
	int n = choices ? (int)g_strv_length((char **)choices) : 0;
	/* The first line is the question, the rest what it's about */
	char **lines = g_strsplit(message ? message : "", "\n", 2);
	ask(m, lines[0], lines[0] && lines[1] ? lines[1] : "", choices, n,
		question_answered);
	g_strfreev(lines);
}

static void aborted(GMountOperation *op, gpointer data) {
	struct mount *m = data;
	if (m->dialog) {
		m->answered = true; // GIO stopped asking: nothing to reply
		c8ui_dialog_close(m->dialog);
	}
}

static void mounted(GObject *source, GAsyncResult *result, gpointer data) {
	struct mount *m = data;
	GError *error = NULL;
	bool ok = g_file_mount_enclosing_volume_finish(G_FILE(source), result,
		&error) || g_error_matches(error, G_IO_ERROR,
		G_IO_ERROR_ALREADY_MOUNTED);
	if (m->dialog) {
		m->dialog->on_destroy = NULL;
		m->answered = true;
		c8ui_dialog_close(m->dialog);
	}
	/* Cancelled by the user: no error to show */
	bool cancelled = g_error_matches(error, G_IO_ERROR,
		G_IO_ERROR_FAILED_HANDLED);
	m->done(ok, ok || cancelled ? NULL : error->message, m->data);
	g_clear_error(&error);
	mounts = g_list_remove(mounts, m);
	g_signal_handlers_disconnect_by_data(m->op, m);
	g_object_unref(m->op);
	g_object_unref(m->location);
	free(m);
}

void mount_location(struct c8ui_root *root, GFile *location, mounted_fn done,
		void *data) {
	struct mount *m = calloc(1, sizeof(*m));
	m->root = root;
	m->location = g_object_ref(location);
	m->done = done;
	m->data = data;
	m->answered = true;
	mounts = g_list_prepend(mounts, m);
	m->op = g_mount_operation_new();
	g_signal_connect(m->op, "ask-password", G_CALLBACK(ask_password), m);
	g_signal_connect(m->op, "ask-question", G_CALLBACK(ask_question), m);
	g_signal_connect(m->op, "aborted", G_CALLBACK(aborted), m);
	g_file_mount_enclosing_volume(location, G_MOUNT_MOUNT_NONE, m->op, NULL,
		mounted, m);
}
