/*
 * Where each app's window was in XR, so it opens there again:
 * ~/.local/state/cont8nuum/holograms.ini, a [app ID] section each with
 * yaw and pitch (degrees, in the recentred world, so forward is wherever
 * you recentre), distance (m), width, height (its pixels) and follow;
 * and stereo (flat, side-by-side or top-bottom: Show as 3D on its slate
 * bar), which an app can have without the rest.
 * Read once, written a second after the last change (a wheel moving a
 * window changes it every notch). The most recently placed are kept.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "server.h"

#define MAX_APPS 256
#define SAVE_DELAY_MS 1000

struct entry {
	char *app_id;
	struct c8_placement p;
};

static struct {
	struct entry items[MAX_APPS]; // oldest first
	int count;
	bool loaded, dirty;
	struct wl_event_source *timer;
} table;

static int find(const char *app_id) {
	for (int i = 0; i < table.count; i++) {
		if (strcmp(table.items[i].app_id, app_id) == 0) {
			return i;
		}
	}
	return -1;
}

/* Out of the table, the rest moved up */
static void take(int i, struct entry *out) {
	*out = table.items[i];
	memmove(&table.items[i], &table.items[i + 1],
		(table.count - i - 1) * sizeof(table.items[0]));
	table.count--;
}

static void append(char *app_id, const struct c8_placement *p) {
	if (table.count == MAX_APPS) {
		struct entry oldest;
		take(0, &oldest);
		free(oldest.app_id);
	}
	table.items[table.count++] = (struct entry){ app_id, *p };
}

/* The section being read; only whole ones count */
struct reading {
	char *app_id;
	struct c8_placement p;
};

static const char *const stereo_names[] = {
	"flat", "side-by-side", "top-bottom",
};

static void finish(struct reading *r) {
	if (r->app_id == NULL) {
		return;
	}
	if (r->p.has_pose && r->p.distance <= 0) {
		r->p.has_pose = false;
	}
	if ((r->p.has_pose || r->p.stereo) && find(r->app_id) < 0) {
		append(r->app_id, &r->p);
	} else {
		free(r->app_id);
	}
	r->app_id = NULL;
}

static void load_handler(void *data, const char *section, const char *key,
		const char *value) {
	struct reading *r = data;
	if (key == NULL) {
		/* A new section: the one before is done */
		finish(r);
		if (strncmp(section, "app ", 4) == 0) {
			const char *id = section + 4;
			while (*id == ' ' || *id == '\t') {
				id++;
			}
			*r = (struct reading){ .app_id = c8_strdup(id) };
		}
		return;
	}
	if (r->app_id == NULL) {
		return;
	}
	struct c8_placement *p = &r->p;
	if (strcmp(key, "yaw") == 0) {
		p->yaw = atof(value) * M_PI / 180;
		p->has_pose = true;
	} else if (strcmp(key, "pitch") == 0) {
		p->pitch = atof(value) * M_PI / 180;
	} else if (strcmp(key, "distance") == 0) {
		p->distance = atof(value);
	} else if (strcmp(key, "width") == 0) {
		p->width = atoi(value);
	} else if (strcmp(key, "height") == 0) {
		p->height = atoi(value);
	} else if (strcmp(key, "follow") == 0) {
		p->follow = strcmp(value, "true") == 0;
	} else if (strcmp(key, "stereo") == 0) {
		for (int i = 0; i < 3; i++) {
			if (strcmp(value, stereo_names[i]) == 0) {
				p->stereo = i;
			}
		}
	}
}

static void load(void) {
	table.loaded = true;
	char path[4200];
	if (!c8_state_path("holograms.ini", path, sizeof(path), false)) {
		return;
	}
	struct reading r = { 0 };
	c8_ini_parse(&r, path, load_handler);
	finish(&r);
}

void c8_placement_flush(void) {
	if (!table.dirty) {
		return;
	}
	table.dirty = false;
	char path[4200], tmp[4210];
	if (!c8_state_path("holograms.ini", path, sizeof(path), true)) {
		return;
	}
	snprintf(tmp, sizeof(tmp), "%s.new", path);
	FILE *f = fopen(tmp, "w");
	if (f == NULL) {
		return;
	}
	fprintf(f, "# Where each app's window was in XR (cont8nuum)\n");
	for (int i = 0; i < table.count; i++) {
		const struct entry *e = &table.items[i];
		fprintf(f, "\n[app %s]\n", e->app_id);
		if (e->p.has_pose) {
			fprintf(f, "yaw = %.2f\npitch = %.2f\ndistance = %.3f\n"
				"width = %d\nheight = %d\nfollow = %s\n",
				e->p.yaw * 180 / M_PI, e->p.pitch * 180 / M_PI,
				e->p.distance, e->p.width, e->p.height,
				e->p.follow ? "true" : "false");
		}
		if (e->p.stereo > 0 && e->p.stereo < 3) {
			fprintf(f, "stereo = %s\n", stereo_names[e->p.stereo]);
		}
	}
	if (fclose(f) == 0) {
		rename(tmp, path);
	} else {
		remove(tmp);
	}
}

static int save_timer(void *data) {
	c8_placement_flush();
	return 0;
}

bool c8_placement_get(const char *app_id, struct c8_placement *out) {
	if (!table.loaded) {
		load();
	}
	int i = app_id && *app_id ? find(app_id) : -1;
	if (i < 0) {
		return false;
	}
	*out = table.items[i].p;
	return true;
}

void c8_placement_put(struct c8_server *server, const char *app_id,
		const struct c8_placement *p) {
	/* An id with a newline or bracket would break the file */
	if (app_id == NULL || *app_id == '\0' || strpbrk(app_id, "[]\n\r")) {
		return;
	}
	if (!table.loaded) {
		load();
	}
	int i = find(app_id);
	char *id;
	if (i >= 0) {
		struct entry e;
		take(i, &e); // to the end: the most recently placed
		id = e.app_id;
	} else {
		id = c8_strdup(app_id);
	}
	append(id, p);
	table.dirty = true;
	if (table.timer == NULL) {
		table.timer = wl_event_loop_add_timer(server->loop, save_timer, NULL);
	}
	if (table.timer) {
		wl_event_source_timer_update(table.timer, SAVE_DELAY_MS);
	} else {
		c8_placement_flush();
	}
}

void c8_placement_put_stereo(struct c8_server *server, const char *app_id,
		int stereo) {
	struct c8_placement p = { 0 };
	c8_placement_get(app_id, &p);
	p.stereo = stereo;
	c8_placement_put(server, app_id, &p);
}
