/*
 * Sound, through the PulseAudio protocol (pipewire-pulse serves it):
 * where sound plays and is recorded, their volume and mute, and each
 * app playing sound with its own volume. Everything is read again a
 * moment after the server says something changed; the controls are
 * updated in place so a slider being dragged stays under the pointer.
 */
#define _GNU_SOURCE
#include <string.h>
#include <pulse/glib-mainloop.h>
#include <pulse/pulseaudio.h>
#include "settings.h"

#define SETTLE_MS 100

struct dev {
	uint32_t index, card;
	char *name, *label;
	pa_cvolume volume;
	bool muted;
};

struct side {
	const char *title, *pick, *none;
	bool input;
	GArray *devs; // struct dev
	char *def;
	struct c8ui_widget *combo, *slider, *mute, *empty;
};

static struct {
	pa_glib_mainloop *loop;
	pa_context *ctx;
	bool ready, failed;
	int waiting; // replies still to come for this read
	bool again;
	guint settle;
	struct side out, in;
	GArray *apps, *new_apps; // struct dev: sink inputs
	GArray *new_sinks, *new_sources;
	char *new_sink, *new_source;
	struct c8ui_widget *page, *status, *apps_box;
} snd = {
	.out = { "Speakers and headphones", "Play sound through",
		"No speakers or headphones were found.", false },
	.in = { "Microphones", "Record from", "No microphones were found.",
		true },
};

static void dev_clear(gpointer data) {
	struct dev *d = data;
	g_free(d->name);
	g_free(d->label);
}

static GArray *dev_list(void) {
	GArray *a = g_array_new(FALSE, TRUE, sizeof(struct dev));
	g_array_set_clear_func(a, dev_clear);
	return a;
}

static int percent(const pa_cvolume *v) {
	return v->channels ? (int)((pa_cvolume_avg(v) * 100.0 + PA_VOLUME_NORM /
		2) / PA_VOLUME_NORM) : 0;
}

static pa_cvolume scaled(const pa_cvolume *v, int pct) {
	pa_cvolume out = *v;
	pa_volume_t to = (pa_volume_t)((double)pct * PA_VOLUME_NORM / 100);
	if (out.channels == 0) {
		pa_cvolume_set(&out, 2, to);
	} else {
		pa_cvolume_scale(&out, to); // keeps the balance
	}
	return out;
}

/* Showing it */

static struct dev *current(struct side *s) {
	for (guint i = 0; s->devs && i < s->devs->len; i++) {
		struct dev *d = &g_array_index(s->devs, struct dev, i);
		if (s->def && strcmp(d->name, s->def) == 0) {
			return d;
		}
	}
	return s->devs && s->devs->len ? &g_array_index(s->devs, struct dev, 0) :
		NULL;
}

static void show_side(struct side *s) {
	if (s->combo == NULL) {
		return;
	}
	int n = s->devs ? (int)s->devs->len : 0, at = -1;
	const char **labels = g_new0(const char *, n + 1);
	struct dev *cur = current(s);
	for (int i = 0; i < n; i++) {
		struct dev *d = &g_array_index(s->devs, struct dev, i);
		labels[i] = d->label;
		if (d == cur) {
			at = i;
		}
	}
	c8ui_combo_set_items(s->combo, labels, n, at);
	g_free(labels);
	s->combo->hidden = n == 0;
	s->slider->hidden = cur == NULL;
	s->mute->hidden = cur == NULL;
	s->empty->hidden = n > 0 || !snd.ready;
	if (cur) {
		c8ui_slider_set(s->slider, percent(&cur->volume));
		c8ui_toggle_set(s->mute, cur->muted);
	}
}

static void app_volume(struct c8ui_widget *w, void *data);

static void show_apps(void) {
	if (snd.apps_box == NULL) {
		return;
	}
	int n = snd.apps ? (int)snd.apps->len : 0;
	/* The same apps: move their sliders; else build them again */
	bool same = snd.apps_box->child_count == n && n > 0;
	for (int i = 0; same && i < n; i++) {
		struct dev *d = &g_array_index(snd.apps, struct dev, i);
		struct c8ui_widget *w = snd.apps_box->children[i];
		same = GPOINTER_TO_UINT(w->user_data) == d->index + 1;
	}
	if (same) {
		for (int i = 0; i < n; i++) {
			struct dev *d = &g_array_index(snd.apps, struct dev, i);
			c8ui_slider_set(snd.apps_box->children[i], percent(&d->volume));
		}
		return;
	}
	c8ui_widget_clear(snd.apps_box);
	if (n == 0) {
		add(snd.apps_box, caption("No apps are playing sound right now."));
		return;
	}
	for (int i = 0; i < n; i++) {
		struct dev *d = &g_array_index(snd.apps, struct dev, i);
		struct c8ui_widget *sl = c8ui_slider_new(d->label, 0, 100, 1,
			percent(&d->volume), app_volume, NULL);
		sl->user_data = GUINT_TO_POINTER(d->index + 1);
		sl->fixed_width = 360;
		add(snd.apps_box, sl);
	}
}

static void show(void) {
	if (snd.page == NULL) {
		return;
	}
	c8ui_label_set_text(snd.status, snd.failed ? "Sound isn't running "
		"(PipeWire, with pipewire-pulse)." : "");
	snd.status->hidden = !snd.failed;
	show_side(&snd.out);
	show_side(&snd.in);
	show_apps();
	c8ui_widget_queue_layout(snd.page);
}

/* Reading it */

static void read_all(void);

/* One card's devices all start with its name ("… HD Audio Speaker",
 * "… HD Audio HDMI 1"): keep what tells them apart */
static void shorten(GArray *devs) {
	size_t *cut = g_new0(size_t, devs->len + 1);
	for (guint i = 0; i < devs->len; i++) {
		struct dev *a = &g_array_index(devs, struct dev, i);
		size_t common = strlen(a->label);
		int others = 0;
		for (guint j = 0; j < devs->len && a->card != PA_INVALID_INDEX; j++) {
			struct dev *b = &g_array_index(devs, struct dev, j);
			if (j == i || b->card != a->card) {
				continue;
			}
			others++;
			size_t k = 0;
			while (k < common && a->label[k] == b->label[k]) {
				k++;
			}
			common = k;
		}
		while (common > 0 && a->label[common - 1] != ' ') {
			common--; // back to the end of a word
		}
		cut[i] = others > 0 && a->label[common] ? common : 0;
	}
	for (guint i = 0; i < devs->len; i++) {
		struct dev *a = &g_array_index(devs, struct dev, i);
		if (cut[i]) {
			char *rest = g_strdup(a->label + cut[i]);
			g_free(a->label);
			a->label = rest;
		}
	}
	g_free(cut);
}

static void got_one(void) {
	if (--snd.waiting > 0) {
		return;
	}
	g_clear_pointer(&snd.out.devs, g_array_unref);
	g_clear_pointer(&snd.in.devs, g_array_unref);
	g_clear_pointer(&snd.apps, g_array_unref);
	shorten(snd.new_sinks);
	shorten(snd.new_sources);
	snd.out.devs = snd.new_sinks;
	snd.in.devs = snd.new_sources;
	snd.apps = snd.new_apps;
	snd.new_sinks = snd.new_sources = snd.new_apps = NULL;
	g_free(snd.out.def);
	g_free(snd.in.def);
	snd.out.def = snd.new_sink;
	snd.in.def = snd.new_source;
	snd.new_sink = snd.new_source = NULL;
	show();
	if (snd.again) {
		snd.again = false;
		read_all();
	}
}

static void got_server(pa_context *c, const pa_server_info *info, void *data) {
	if (info) {
		snd.new_sink = g_strdup(info->default_sink_name);
		snd.new_source = g_strdup(info->default_source_name);
	}
	got_one();
}

static void got_sink(pa_context *c, const pa_sink_info *info, int eol,
		void *data) {
	if (eol) {
		got_one();
		return;
	}
	struct dev d = { info->index, info->card, g_strdup(info->name),
		g_strdup(info->description ? info->description : info->name),
		info->volume, info->mute };
	g_array_append_val(snd.new_sinks, d);
}

static void got_source(pa_context *c, const pa_source_info *info, int eol,
		void *data) {
	if (eol) {
		got_one();
		return;
	}
	/* What a speaker plays isn't a microphone */
	if (info->monitor_of_sink != PA_INVALID_INDEX) {
		return;
	}
	struct dev d = { info->index, info->card, g_strdup(info->name),
		g_strdup(info->description ? info->description : info->name),
		info->volume, info->mute };
	g_array_append_val(snd.new_sources, d);
}

static void got_input(pa_context *c, const pa_sink_input_info *info, int eol,
		void *data) {
	if (eol) {
		got_one();
		return;
	}
	const char *app = pa_proplist_gets(info->proplist,
		PA_PROP_APPLICATION_NAME);
	const char *role = pa_proplist_gets(info->proplist, PA_PROP_MEDIA_ROLE);
	/* Clicks and beeps come and go too quickly to set */
	if (role && strcmp(role, "event") == 0) {
		return;
	}
	struct dev d = { info->index, PA_INVALID_INDEX, NULL, g_strdup(app ? app : info->name ?
		info->name : "An app"), info->volume, info->mute };
	g_array_append_val(snd.new_apps, d);
}

static void track(pa_operation *op) {
	if (op) {
		pa_operation_unref(op);
		snd.waiting++;
	}
}

static void read_all(void) {
	if (!snd.ready) {
		return;
	}
	if (snd.waiting > 0) {
		snd.again = true;
		return;
	}
	snd.new_sinks = dev_list();
	snd.new_sources = dev_list();
	snd.new_apps = dev_list();
	snd.waiting = 1; // till all four are asked
	track(pa_context_get_server_info(snd.ctx, got_server, NULL));
	track(pa_context_get_sink_info_list(snd.ctx, got_sink, NULL));
	track(pa_context_get_source_info_list(snd.ctx, got_source, NULL));
	track(pa_context_get_sink_input_info_list(snd.ctx, got_input, NULL));
	got_one();
}

static gboolean settled(gpointer data) {
	snd.settle = 0;
	read_all();
	return G_SOURCE_REMOVE;
}

static void changed(pa_context *c, pa_subscription_event_type_t type,
		uint32_t index, void *data) {
	if (snd.settle == 0) {
		snd.settle = g_timeout_add(SETTLE_MS, settled, NULL);
	}
}

static void connect_server(void);

static gboolean reconnect(gpointer data) {
	connect_server();
	return G_SOURCE_REMOVE;
}

static void state_changed(pa_context *c, void *data) {
	switch (pa_context_get_state(c)) {
	case PA_CONTEXT_READY:
		snd.ready = true;
		snd.failed = false;
		pa_context_set_subscribe_callback(c, changed, NULL);
		pa_operation_unref(pa_context_subscribe(c, PA_SUBSCRIPTION_MASK_SINK |
			PA_SUBSCRIPTION_MASK_SOURCE | PA_SUBSCRIPTION_MASK_SINK_INPUT |
			PA_SUBSCRIPTION_MASK_SERVER, NULL, NULL));
		read_all();
		break;
	case PA_CONTEXT_FAILED:
	case PA_CONTEXT_TERMINATED:
		/* The server went (restarted, say): try again in a moment */
		snd.ready = false;
		snd.failed = true;
		snd.waiting = 0;
		snd.again = false;
		g_clear_pointer(&snd.new_sinks, g_array_unref);
		g_clear_pointer(&snd.new_sources, g_array_unref);
		g_clear_pointer(&snd.new_apps, g_array_unref);
		g_clear_pointer(&snd.new_sink, g_free);
		g_clear_pointer(&snd.new_source, g_free);
		pa_context_unref(snd.ctx);
		snd.ctx = NULL;
		show();
		g_timeout_add_seconds(3, reconnect, NULL);
		break;
	default:
		break;
	}
}

static void connect_server(void) {
	if (snd.ctx) {
		return;
	}
	if (snd.loop == NULL) {
		snd.loop = pa_glib_mainloop_new(NULL);
	}
	pa_proplist *props = pa_proplist_new();
	pa_proplist_sets(props, PA_PROP_APPLICATION_NAME, "PC settings");
	pa_proplist_sets(props, PA_PROP_APPLICATION_ID, "c8-settings");
	snd.ctx = pa_context_new_with_proplist(pa_glib_mainloop_get_api(snd.loop),
		"PC settings", props);
	pa_proplist_free(props);
	pa_context_set_state_callback(snd.ctx, state_changed, NULL);
	/* Failing at once may already have run state_changed, which let the
	 * context go */
	pa_context *c = snd.ctx;
	if (pa_context_connect(c, NULL, PA_CONTEXT_NOFAIL, NULL) < 0 &&
			snd.ctx == c) {
		state_changed(c, NULL);
	}
}

/* Changing it */

static void picked(struct c8ui_widget *w, void *data) {
	struct side *s = data;
	int i = c8ui_combo_get(w);
	if (!snd.ready || s->devs == NULL || i < 0 || i >= (int)s->devs->len) {
		return;
	}
	const char *name = g_array_index(s->devs, struct dev, i).name;
	pa_operation *op = s->input ?
		pa_context_set_default_source(snd.ctx, name, NULL, NULL) :
		pa_context_set_default_sink(snd.ctx, name, NULL, NULL);
	if (op) {
		pa_operation_unref(op);
	}
}

static void volume(struct c8ui_widget *w, void *data) {
	struct side *s = data;
	struct dev *d = current(s);
	if (!snd.ready || d == NULL) {
		return;
	}
	d->volume = scaled(&d->volume, (int)c8ui_slider_get(w));
	pa_operation *op = s->input ?
		pa_context_set_source_volume_by_index(snd.ctx, d->index, &d->volume,
			NULL, NULL) :
		pa_context_set_sink_volume_by_index(snd.ctx, d->index, &d->volume,
			NULL, NULL);
	if (op) {
		pa_operation_unref(op);
	}
}

static void mute(struct c8ui_widget *w, void *data) {
	struct side *s = data;
	struct dev *d = current(s);
	if (!snd.ready || d == NULL) {
		return;
	}
	d->muted = c8ui_toggle_get(w);
	pa_operation *op = s->input ?
		pa_context_set_source_mute_by_index(snd.ctx, d->index, d->muted, NULL,
			NULL) :
		pa_context_set_sink_mute_by_index(snd.ctx, d->index, d->muted, NULL,
			NULL);
	if (op) {
		pa_operation_unref(op);
	}
}

static void app_volume(struct c8ui_widget *w, void *data) {
	uint32_t index = GPOINTER_TO_UINT(w->user_data) - 1;
	for (guint i = 0; snd.ready && snd.apps && i < snd.apps->len; i++) {
		struct dev *d = &g_array_index(snd.apps, struct dev, i);
		if (d->index == index) {
			d->volume = scaled(&d->volume, (int)c8ui_slider_get(w));
			pa_operation *op = pa_context_set_sink_input_volume(snd.ctx,
				index, &d->volume, NULL, NULL);
			if (op) {
				pa_operation_unref(op);
			}
		}
	}
}

/* The page */

static void build_side(struct c8ui_widget *page, struct side *s) {
	add(page, section_title(s->title));
	s->combo = c8ui_combo_new(s->pick, NULL, 0, -1, picked, s);
	add(page, s->combo);
	s->slider = c8ui_slider_new("Volume", 0, 100, 1, 0, volume, s);
	s->slider->fixed_width = 360;
	add(page, s->slider);
	s->mute = c8ui_toggle_new("Mute", NULL, false, mute, s);
	add(page, s->mute);
	s->empty = caption(s->none);
	s->empty->hidden = true;
	add(page, s->empty);
}

static void page_gone(struct c8ui_widget *w, void *data) {
	snd.page = snd.status = snd.apps_box = NULL;
	snd.out.combo = snd.out.slider = snd.out.mute = snd.out.empty = NULL;
	snd.in.combo = snd.in.slider = snd.in.mute = snd.in.empty = NULL;
}

static void sound_build(struct c8ui_widget *box) {
	snd.page = c8ui_box_new(C8UI_VERTICAL, 18);
	snd.page->fill = true;
	snd.page->on_destroy = page_gone;
	add(box, snd.page);
	snd.status = caption("");
	snd.status->hidden = true;
	add(snd.page, snd.status);
	build_side(snd.page, &snd.out);
	build_side(snd.page, &snd.in);
	add(snd.page, section_title("Apps"));
	snd.apps_box = c8ui_box_new(C8UI_VERTICAL, 12);
	add(snd.page, snd.apps_box);
	connect_server();
	show();
	read_all();
}

const struct page page_sound = {
	.name = "sound",
	.title = "Sound",
	.build = sound_build,
};
