/*
 * Default apps: which app opens links, mail, music and the rest, and
 * which terminal Super+Enter runs. One tile per kind, as Windows 8.1's
 * Defaults page has them: the app's icon and name on the accent colour;
 * a click lists the apps that can do it. The choice goes into
 * mimeapps.list through GIO, like any desktop's, so xdg-open and every
 * app follow it; the terminal is [general] terminal. The kinds are
 * c8-base's list (default-apps.h), which the shell's All apps entries and
 * tiles come from too.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "settings.h"
#include "default-apps.h"

#define TILE_W 310
#define TILE_H 80
#define ICON 40
#define LIST_H 300

#define ROLE_COUNT C8_DEFAULT_ROLES

struct tile {
	const struct c8_default_role *role;
	struct c8ui_widget *w;
	GAppInfo *app; // the default now, or NULL
	char *label, *icon;
	struct c8ui_icon_request *req;
	cairo_surface_t *image;
	bool fallback; // the role's own icon is being fetched
};

static struct {
	struct tile *tiles[ROLE_COUNT];
	char terminal[256]; // the setting the Terminal tile shows
} page;

/* The terminal */

static void first_word(const char *s, char *out, size_t len) {
	size_t n = strcspn(s, " \t");
	snprintf(out, len, "%.*s", (int)n, s);
}

static const char *base_name(const char *path) {
	const char *slash = strrchr(path, '/');
	return slash ? slash + 1 : path;
}

static bool is_terminal(GAppInfo *info) {
	if (!G_IS_DESKTOP_APP_INFO(info) || !g_app_info_should_show(info)) {
		return false;
	}
	const char *cats = g_desktop_app_info_get_categories(
		G_DESKTOP_APP_INFO(info));
	if (cats == NULL) {
		return false;
	}
	char **list = g_strsplit(cats, ";", -1);
	bool yes = g_strv_contains((const char *const *)list, "TerminalEmulator");
	g_strfreev(list);
	return yes;
}

/* The terminal emulator whose program [general] terminal names */
static GAppInfo *terminal_app(void) {
	char prog[256];
	first_word(setting_or("general", "terminal", ""), prog, sizeof(prog));
	if (prog[0] == '\0') {
		return NULL;
	}
	/* Several entries can run the same program (foot, foot --server):
	 * the one named after it, else the one with the shortest command */
	GAppInfo *found = NULL;
	size_t found_len = 0;
	bool found_named = false;
	char named[300];
	snprintf(named, sizeof(named), "%s.desktop", base_name(prog));
	GList *all = g_app_info_get_all();
	for (GList *l = all; l; l = l->next) {
		const char *exe = g_app_info_get_executable(l->data);
		const char *cmd = g_app_info_get_commandline(l->data);
		if (exe == NULL || cmd == NULL || !is_terminal(l->data) ||
				strcmp(base_name(exe), base_name(prog)) != 0) {
			continue;
		}
		const char *id = g_app_info_get_id(l->data);
		bool is_named = id && strcmp(id, named) == 0;
		if (found == NULL || (is_named && !found_named) ||
				(!found_named && strlen(cmd) < found_len)) {
			g_clear_object(&found);
			found = g_object_ref(l->data);
			found_len = strlen(cmd);
			found_named = is_named;
		}
	}
	g_list_free_full(all, g_object_unref);
	return found;
}

/* The tile */

static void icon_loaded(void *data, cairo_surface_t *image);

static void request_icon(struct tile *t, const char *name) {
	c8ui_icon_request_cancel(t->req);
	/* Twice the size: crisp on a 2x screen, scaled down on others */
	t->req = c8ui_icon_request(setting("general", "icon_theme"), name,
		ICON * 2, true, icon_loaded, t);
}

static void icon_loaded(void *data, cairo_surface_t *image) {
	struct tile *t = data;
	t->req = NULL;
	if (image == NULL && !t->fallback) {
		/* The app's icon isn't installed: the kind's own */
		t->fallback = true;
		request_icon(t, t->role->icon);
		return;
	}
	if (t->image) {
		cairo_surface_destroy(t->image);
	}
	t->image = image;
	c8ui_widget_queue_draw(t->w);
}

static char *app_icon_name(GAppInfo *app) {
	GIcon *icon = g_app_info_get_icon(app);
	if (G_IS_THEMED_ICON(icon)) {
		const char *const *names = g_themed_icon_get_names(G_THEMED_ICON(icon));
		if (names && names[0]) {
			return strdup(names[0]);
		}
	} else if (G_IS_FILE_ICON(icon)) {
		return g_file_get_path(g_file_icon_get_file(G_FILE_ICON(icon)));
	}
	return NULL;
}

/* Reads the role's default again and shows it */
static void tile_load(struct tile *t) {
	g_clear_object(&t->app);
	free(t->label);
	free(t->icon);
	t->label = t->icon = NULL;
	if (t->image) {
		cairo_surface_destroy(t->image);
		t->image = NULL;
	}
	t->fallback = false;

	const struct c8_default_role *role = t->role;
	if (role->types) {
		char first[128];
		snprintf(first, sizeof(first), "%.*s",
			(int)strcspn(role->types, ";"), role->types);
		t->app = g_app_info_get_default_for_type(first, FALSE);
	} else {
		t->app = terminal_app();
		first_word(setting_or("general", "terminal", ""), page.terminal,
			sizeof(page.terminal));
	}
	if (t->app) {
		t->label = strdup(g_app_info_get_display_name(t->app));
		t->icon = app_icon_name(t->app);
	} else if (role->types == NULL && page.terminal[0]) {
		/* A terminal with no desktop entry: the command as typed */
		t->label = strdup(page.terminal);
	} else {
		t->label = strdup("Choose a default");
	}
	if (t->icon == NULL) {
		t->icon = strdup(role->icon);
		t->fallback = true;
	}
	request_icon(t, t->icon);
	c8ui_widget_queue_draw(t->w);
}

static void tile_measure(struct c8ui_widget *w, double avail_width,
		double *width, double *height) {
	*width = TILE_W;
	*height = TILE_H;
}

static void tile_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct tile *t = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	uint32_t bg = c.accent;
	if (w->pressed) {
		bg = c8ui_shade(bg, 0.8);
	} else if (w->hovered) {
		bg = c8ui_shade(bg, 1.15);
	}
	c8ui_set_source(cr, bg, 1);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_fill(cr);

	double ix = w->rect.x + 20, iy = w->rect.y + (TILE_H - ICON) / 2.0;
	if (t->image) {
		int px = cairo_image_surface_get_width(t->image);
		double s = px > 0 ? (double)ICON / px : 1;
		c8ui_draw_surface(cr, t->image, ix, iy, px * s,
			cairo_image_surface_get_height(t->image) * s);
	} else if (t->app == NULL) {
		/* Nothing chosen and no icon: an empty frame with a plus */
		cairo_set_source_rgba(cr, 1, 1, 1, 0.8);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, ix + 1, iy + 1, ICON - 2, ICON - 2);
		cairo_stroke(cr);
		cairo_move_to(cr, ix + ICON / 2.0, iy + 10);
		cairo_line_to(cr, ix + ICON / 2.0, iy + ICON - 10);
		cairo_move_to(cr, ix + 10, iy + ICON / 2.0);
		cairo_line_to(cr, ix + ICON - 10, iy + ICON / 2.0);
		cairo_stroke(cr);
	}

	const char *family = c8ui_root_theme(w->root)->font;
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_ITEM);
	double tx = ix + ICON + 16, tw = w->rect.x + w->rect.width - tx - 12;
	double unused, th;
	c8ui_text_size(family, font, t->label, tw, 1, &unused, &th);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, font, t->label, tx,
		w->rect.y + (TILE_H - th) / 2, tw, 1);
}

static void pick_show(struct tile *t);

static bool tile_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct tile *t = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		c8ui_widget_grab_focus(w);
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_RELEASE:
		c8ui_widget_queue_draw(w);
		if (ev->x >= w->rect.x && ev->x < w->rect.x + w->rect.width &&
				ev->y >= w->rect.y && ev->y < w->rect.y + w->rect.height) {
			pick_show(t);
		}
		return true;
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
				ev->sym == XKB_KEY_space) {
			pick_show(t);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void tile_destroy(struct c8ui_widget *w) {
	struct tile *t = w->data;
	c8ui_icon_request_cancel(t->req);
	if (t->image) {
		cairo_surface_destroy(t->image);
	}
	g_clear_object(&t->app);
	free(t->label);
	free(t->icon);
	for (int i = 0; i < ROLE_COUNT; i++) {
		if (page.tiles[i] == t) {
			page.tiles[i] = NULL;
		}
	}
	free(t);
}

static const struct c8ui_widget_impl tile_impl = {
	.name = "default-tile",
	.measure = tile_measure,
	.draw = tile_draw,
	.event = tile_event,
	.destroy = tile_destroy,
};

static struct tile *tile_new(const struct c8_default_role *role) {
	struct tile *t = calloc(1, sizeof(*t));
	t->role = role;
	t->w = c8ui_widget_new(&tile_impl, t);
	t->w->focusable = true;
	t->w->cursor = C8UI_CURSOR_POINTER;
	tile_load(t);
	return t;
}

/* Choosing */

struct pick {
	struct tile *t;
	struct c8ui_widget *flyout, *nav, *more;
	GPtrArray *apps; // GAppInfo, in the nav's order
};

static void pick_add(struct pick *p, GAppInfo *app) {
	if (!g_app_info_should_show(app)) {
		return;
	}
	for (guint i = 0; i < p->apps->len; i++) {
		if (g_app_info_equal(p->apps->pdata[i], app)) {
			return;
		}
	}
	g_ptr_array_add(p->apps, g_object_ref(app));
	c8ui_nav_add(p->nav, g_app_info_get_display_name(app));
}

static int by_name(gconstpointer a, gconstpointer b) {
	return g_utf8_collate(g_app_info_get_display_name((GAppInfo *)a),
		g_app_info_get_display_name((GAppInfo *)b));
}

static void pick_add_list(struct pick *p, GList *apps) {
	for (GList *l = apps; l; l = l->next) {
		pick_add(p, l->data);
	}
	g_list_free_full(apps, g_object_unref);
}

/* The apps that say they can: handlers of the first type, or terminals */
static void pick_candidates(struct pick *p) {
	const struct c8_default_role *role = p->t->role;
	if (role->types == NULL) {
		GList *all = g_list_sort(g_app_info_get_all(), by_name);
		for (GList *l = all; l; l = l->next) {
			if (is_terminal(l->data)) {
				pick_add(p, l->data);
			}
		}
		g_list_free_full(all, g_object_unref);
		return;
	}
	char first[128];
	snprintf(first, sizeof(first), "%.*s", (int)strcspn(role->types, ";"),
		role->types);
	if (p->t->app) {
		pick_add(p, p->t->app);
	}
	pick_add_list(p, g_app_info_get_recommended_for_type(first));
	pick_add_list(p, g_app_info_get_fallback_for_type(first));
}

static void pick_more(struct c8ui_widget *link, void *data) {
	struct pick *p = data;
	link->hidden = true;
	pick_add_list(p, g_list_sort(g_app_info_get_all(), by_name));
	c8ui_widget_queue_layout(p->nav);
}

static void make_default(struct tile *t, GAppInfo *app) {
	const struct c8_default_role *role = t->role;
	if (role->types == NULL) {
		const char *exe = g_app_info_get_executable(app);
		if (exe) {
			setting_set("general", "terminal", exe);
		}
		return;
	}
	char **types = g_strsplit(role->types, ";", -1);
	/* The first type (the one read back) always; the rest only if the
	 * app says it opens them: a viewer without JPEG XL shouldn't take
	 * it from one that has it. An app that lists none takes them all. */
	const char **can = g_app_info_get_supported_types(app);
	GError *error = NULL;
	for (char **type = types; *type; type++) {
		if (type != types && can && can[0] &&
				!g_strv_contains(can, *type)) {
			continue;
		}
		if (!g_app_info_set_as_default_for_type(app, *type, &error)) {
			show_error("Can't change the default", error->message);
			g_error_free(error);
			break;
		}
	}
	g_strfreev(types);
}

static void pick_chosen(struct c8ui_widget *nav, void *data) {
	struct pick *p = data;
	int i = c8ui_nav_get(nav);
	if (i < 0 || i >= (int)p->apps->len) {
		return;
	}
	make_default(p->t, p->apps->pdata[i]);
	tile_load(p->t);
	c8ui_flyout_close(p->flyout); // closed: freed
}

static void pick_closed(void *data) {
	struct pick *p = data;
	g_ptr_array_unref(p->apps);
	free(p);
}

static void pick_show(struct tile *t) {
	struct pick *p = calloc(1, sizeof(*p));
	p->t = t;
	p->apps = g_ptr_array_new_with_free_func(g_object_unref);

	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	box->fixed_width = 360;
	char *kind = g_ascii_strdown(t->role->name, -1);
	char *title = g_strdup_printf("Choose an app for %s",
		t->role->types ? kind : "the terminal");
	c8ui_widget_add(box, c8ui_label_new(title, C8UI_TEXT_TITLE));
	g_free(title);
	g_free(kind);

	p->nav = c8ui_nav_new(pick_chosen, p);
	pick_candidates(p);
	c8ui_nav_set(p->nav, -1);
	struct c8ui_widget *scroll = c8ui_scroll_new(p->nav);
	scroll->fixed_height = LIST_H;
	scroll->fill = true;
	c8ui_widget_add(box, scroll);

	p->more = c8ui_link_new("More apps", pick_more, p);
	c8ui_widget_add(box, p->more);
	if (p->apps->len == 0) {
		pick_more(p->more, p); // nothing says it can: offer everything
	}
	p->flyout = c8ui_flyout_show(app.root, &t->w->rect, box, pick_closed, p);
}

/* The page */

static void defaults_gone(struct c8ui_widget *w, void *data) {
	memset(page.tiles, 0, sizeof(page.tiles));
}

static void defaults_build(struct c8ui_widget *box) {
	add(box, caption("Links, files and the terminal open in these apps. "
		"Pick one to change it; for other kinds of file, use Open with "
		"in Files."));
	for (int i = 0; i < ROLE_COUNT; i++) {
		struct c8ui_widget *one = c8ui_box_new(C8UI_VERTICAL, 8);
		c8ui_widget_add(one, c8ui_label_new(c8_default_roles[i].name, C8UI_TEXT_BODY));
		page.tiles[i] = tile_new(&c8_default_roles[i]);
		c8ui_widget_add(one, page.tiles[i]->w);
		add(box, one);
	}
	box->on_destroy = defaults_gone;
}

/* The terminal setting changed under us (the General page, a config
 * reload): show the new one */
static void defaults_refresh(void) {
	char prog[256];
	first_word(setting_or("general", "terminal", ""), prog, sizeof(prog));
	if (strcmp(prog, page.terminal) == 0) {
		return;
	}
	for (int i = 0; i < ROLE_COUNT; i++) {
		if (page.tiles[i] && c8_default_roles[i].types == NULL) {
			tile_load(page.tiles[i]);
		}
	}
}

const struct page page_defaults = {
	.name = "defaults",
	.title = "Default apps",
	.build = defaults_build,
	.refresh = defaults_refresh,
};
