# Write the XDG desktop file for the given application
# USAGE: launcher_write_desktop $package $application
launcher_write_desktop() {
	local package application
	package="$1"
	application="$2"

	local desktop_file desktop_directory
	desktop_file=$(launcher_desktop_filepath "$package" "$application")
	desktop_directory=$(dirname "$desktop_file")
	mkdir --parents "$desktop_directory"
	(
		set_current_package "$package"
		launcher_desktop "$application" > "$desktop_file"
	)
}

# Print the content of the XDG desktop file for the given application
# USAGE: launcher_desktop $application
# RETURN: the full content of the XDG desktop file
launcher_desktop() {
	local application
	application="$1"

	local application_name application_category desktop_field_exec desktop_field_icon
	application_name=$(application_name "$application")
	application_category=$(application_category "$application")
	desktop_field_exec=$(desktop_field_exec "$application")
	desktop_field_icon=$(desktop_field_icon "$application")

	cat <<- EOF
	[Desktop Entry]
	Version=1.0
	Type=Application
	Name=$application_name
	Icon=$desktop_field_icon
	Exec=$desktop_field_exec
	Categories=$application_category
	EOF
}

# Print the full path to the XDG desktop file for the given application
# USAGE: launcher_desktop_filepath $package $application
# RETURN: an absolute file path
launcher_desktop_filepath() {
	local package application
	package="$1"
	application="$2"

	local application_id package_path path_xdg_desktop
	application_id=$(
		set_current_package "$package"
		application_id "$application"
	)
	package_path=$(package_path "$package")
	path_xdg_desktop=$(path_xdg_desktop)

	printf '%s/%s.desktop' \
		"${package_path}${path_xdg_desktop}" \
		"$application_id"
}

# Print the XDG desktop "Exec" field for the given application
# USAGE: desktop_field_exec $application
# RETURN: The "Exec" field content, including escaping if required
desktop_field_exec() {
	local application
	application="$1"

	local option_prefix application_id exec_field
	option_prefix=$(option_value 'prefix')
	application_id=$(application_id "$application")
	case "$option_prefix" in
		## Standard path, only the command name is required.
		('/usr'|'/usr/local')
			exec_field="$application_id"
		;;
		## Non-standard path including spaces, the full path enclosed in quotes is required.
		(*' '*)
			local path_binaries
			path_binaries=$(path_binaries)
			exec_field="'${path_binaries}/${application_id}'"
		;;
		## Non-standard path not including spaces, the full path is required.
		(*)
			local path_binaries
			path_binaries=$(path_binaries)
			exec_field="${path_binaries}/${application_id}"
		;;
	esac

	printf '%s' "$exec_field"
}

# Print the XDG desktop "Icon" field for the given application
# USAGE: desktop_field_icon $application
# RETURN: The "Icon" field content
desktop_field_icon() {
	local application
	application="$1"

	local icon_field
	icon_field=$(application_id "$application")

	printf '%s' "$icon_field"
}

