/*
 * Copyright (c) 2019 - 2025 Andri Yngvason
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#include <neatvnc.h>

#include <stdio.h>
#include <aml.h>
#include <signal.h>
#include <assert.h>
#include <pixman.h>

struct nvnc_frame* read_png_file(const char* filename);

static void on_sigint()
{
	aml_exit(aml_get_default());
}

int main(int argc, char* argv[])
{
	int ret = 1;

	if (argc < 2) {
		printf("Missing argument\n");
		return 1;
	}

	struct aml* aml = aml_new();
	aml_set_default(aml);

	struct nvnc* server = nvnc_new();
	assert(server);

	int x_pos = 0;
	for (int i = 1; i < argc; ++i) {
		const char* file = argv[i];
		printf("Adding %s\n", file);

		struct nvnc_frame* fb = read_png_file(file);
		if (!fb) {
			printf("Failed to read png file: %s\n", file);
			goto out;
		}

		struct nvnc_display* display = nvnc_display_new(x_pos, 0);
		assert(display);

		x_pos += nvnc_frame_get_width(fb);

		nvnc_add_display(server, display);
		nvnc_set_name(server, file);

		nvnc_display_feed_frame(display, fb);

		nvnc_display_unref(display);
		nvnc_frame_unref(fb);
	}

	int rc = nvnc_listen_tcp(server, "127.0.0.1", 5900, NVNC_STREAM_NORMAL);
	nvnc_assert(rc == 0, "Failed to create listening socket");

	struct aml_signal* sig = aml_signal_new(SIGINT, on_sigint, NULL, NULL);
	aml_start(aml_get_default(), sig);
	aml_unref(sig);

	aml_run(aml);

	ret = 0;
out:
	nvnc_del(server);
	aml_unref(aml);

	return ret;
}
