#include <stdio.h>
#include <unistd.h>

#include <vali.h>

#include "example.h"

static void handle_monitor(struct ftl_Monitor_service_call call, const struct ftl_Monitor_in *in) {
	struct ftl_Monitor_out out = {
		.condition = {
			.state = ftl_DriveCondition_state_idle,
			.tylium_level = 42,
		},
	};
	ftl_Monitor_close_with_reply(call, &out);
}

static void handle_calculate_configuration(struct ftl_CalculateConfiguration_service_call call, const struct ftl_CalculateConfiguration_in *in) {
	struct ftl_CalculateConfiguration_out out = {
		.configuration = {
			.speed = 1,
			.trajectory = 2,
			.duration = 3,
		},
	};
	ftl_CalculateConfiguration_close_with_reply(call, &out);
}

static void handle_jump(struct ftl_Jump_service_call call, const struct ftl_Jump_in *in) {
	const struct ftl_DriveConfiguration *config = &in->configuration;
	printf("Jump: speed=%d, trajectory=%d, duration=%d\n", config->speed, config->trajectory, config->duration);
	ftl_Jump_close_with_reply(call, NULL);
}

static const struct ftl_handler ftl_handler = {
	.Monitor = handle_monitor,
	.CalculateConfiguration = handle_calculate_configuration,
	.Jump = handle_jump,
};

int main(int argc, char *argv[]) {
	if (argc != 2) {
		fprintf(stderr, "usage: service <socket>\n");
		return 1;
	}
	const char *socket_path = argv[1];

	struct vali_service *service = vali_service_create();

	const struct vali_registry_options registry_options = {
		.vendor = "FooCorp",
		.product = "example",
		.version = "1.0",
		.url = "https://example.org",
	};
	struct vali_registry *registry = vali_registry_create(&registry_options);
	vali_registry_add(registry, &ftl_interface, ftl_get_call_handler(&ftl_handler));
	vali_service_set_call_handler(service, vali_registry_get_call_handler(registry));

	unlink(socket_path);
	if (!vali_service_listen_unix(service, socket_path)) {
		fprintf(stderr, "Failed to listen on Unix socket %s\n", socket_path);
		return 1;
	}

	while (vali_service_dispatch(service));

	vali_service_destroy(service);

	return 0;
}
