/*
 * Default apps: the kinds of thing PC settings' Default apps page gives an
 * app to (web browser, mail, music, ...). Each is an entry in All apps and
 * so a tile, which opens whatever app is the default for it when it's
 * used, not when it was pinned: `@default ROLE` is resolved here, from the
 * mimeapps.list defaults GIO reads (the same ones xdg-open follows). The
 * terminal is the compositor's own `@terminal`. The roles are c8-base's
 * list (default-apps.h), which c8-settings' page, what sets them, uses too.
 */
#include <gio/gdesktopappinfo.h>
#include "shell.h"

int defaults_count(void) {
	return C8_DEFAULT_ROLES;
}

const struct c8_default_role *defaults_role(int i) {
	return &c8_default_roles[i];
}

/* The command of the app that is the default for a role now, or NULL */
static char *default_command(const struct c8_default_role *role) {
	if (role->type == NULL) {
		return strdup("@terminal");
	}
	GAppInfo *info = g_app_info_get_default_for_type(role->type, FALSE);
	if (info == NULL) {
		return NULL;
	}
	char *cmd = NULL;
	const char *path = G_IS_DESKTOP_APP_INFO(info) ?
		g_desktop_app_info_get_filename(G_DESKTOP_APP_INFO(info)) : NULL;
	if (path) {
		cmd = apps_command(path);
	}
	g_object_unref(info);
	return cmd;
}

void shell_launch(const char *exec) {
	if (strncmp(exec, "@default ", 9) != 0) {
		c8_shell_v1_launch(shell.proto, exec);
		return;
	}
	const char *id = exec + 9;
	for (size_t i = 0; i < G_N_ELEMENTS(c8_default_roles); i++) {
		if (strcmp(c8_default_roles[i].id, id) != 0) {
			continue;
		}
		char *cmd = default_command(&c8_default_roles[i]);
		if (cmd) {
			c8_shell_v1_launch(shell.proto, cmd);
			free(cmd);
		} else {
			/* Nothing is: the page to choose one */
			c8_shell_v1_launch(shell.proto, "c8-settings --page defaults");
		}
		return;
	}
	g_warning("No such default app: %s", id);
}
