#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>

#include <vali.h>

#include "ipc.h"
#include "ipc-gen.h"

static void usage(void) {
	fprintf(stderr, "Usage: kanshictl [command]\n"
		"\n"
		"Commands:\n"
		"  reload            Reload the configuration file\n"
		"  switch <profile>  Switch to another profile\n"
		"  status            Print current state\n");
}

static void print_ipc_error(const struct vali_error *err) {
	if (strcmp(err->name, "fr.emersion.kanshi.ProfileNotFound") == 0) {
		fprintf(stderr, "Profile not found\n");
	} else if (strcmp(err->name, "fr.emersion.kanshi.ProfileNotMatched") == 0) {
		fprintf(stderr, "Profile does not match the current output configuration\n");
	} else if (strcmp(err->name, "fr.emersion.kanshi.ProfileNotApplied") == 0) {
		fprintf(stderr, "Profile could not be applied by the compositor\n");
	} else {
		fprintf(stderr, "Error: %s\n", err->name);
	}
}

int main(int argc, char *argv[]) {
	if (argc < 2) {
		usage();
		return EXIT_FAILURE;
	}
	if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
		usage();
		return EXIT_SUCCESS;
	}

	char path[PATH_MAX];
	if (get_ipc_path(path, sizeof(path)) < 0) {
		return EXIT_FAILURE;
	}
	struct vali_client *client = vali_client_connect_unix(path);
	if (client == NULL) {
		fprintf(stderr, "Couldn't connect to kanshi at %s.\n"
				"Is the kanshi daemon running?\n", path);
		return EXIT_FAILURE;
	}

	const char *command = argv[1];
	bool ok;
	struct vali_error err = {0};
	if (strcmp(command, "reload") == 0) {
		ok = ipc_Reload(client, NULL, NULL, &err);
	} else if (strcmp(command, "status") == 0) {
		struct ipc_Status_out out = {0};
		ok = ipc_Status(client, NULL, &out, &err);
		if (ok) {
			printf("Current profile: %s\n", out.current_profile ? out.current_profile : "(none)");
			if (out.pending_profile != NULL &&
					(out.current_profile == NULL || strcmp(out.pending_profile, out.current_profile) != 0)) {
				printf("Pending profile: %s\n", out.pending_profile);
			}
		}
		ipc_Status_out_finish(&out);
	} else if (strcmp(command, "switch") == 0) {
		if (argc < 3) {
			usage();
			return EXIT_FAILURE;
		}

		const struct ipc_Switch_in in = {
			.profile = argv[2],
		};
		ok = ipc_Switch(client, &in, NULL, &err);
	} else {
		fprintf(stderr, "invalid command: %s\n", argv[1]);
		usage();
		return EXIT_FAILURE;
	}

	vali_client_destroy(client);

	if (!ok) {
		if (err.name != NULL) {
			print_ipc_error(&err);
		} else {
			fprintf(stderr, "IPC error\n");
		}
		vali_error_finish(&err);
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
