// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright © 2020-2021 Florian Fischer
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include "CountingPrivateSemaphore.hpp"
#include "Fiber.hpp"
#include "Runtime.hpp"
#include "emper.hpp"
#include "fixtures/network.hpp"
#include "io.hpp"

#define PORT 4241
#define BUF_SIZE 1024

auto main(int argc, char* argv[]) -> int {
	unsigned int client_count = 10;
	unsigned int echos = 1000;
	int port = PORT;
	std::string host = "127.0.0.1";

	if (argc > 3) {
		std::cerr << "Usage: " << argv[0] << " [clients] [echos]" << std::endl;
		exit(EXIT_FAILURE);
	}

	const int DECIMAL = 10;
	if (argc > 1) {
		client_count = strtol(argv[1], nullptr, DECIMAL);
	}

	if (argc > 2) {
		echos = strtol(argv[2], nullptr, DECIMAL);
	}

	Runtime runtime;

	runtime.scheduleFromAnywhere(*emper::io::tcp_listener(host, port, echo_serve));

	Fiber* client_producer = Fiber::from([&] {
		CPS cps;
		for (unsigned int i = 0; i < client_count; ++i) {
			spawn(
					[&] {
						const std::vector<std::string> msgs = {"foo"};
						echo_client("127.0.0.1", PORT, msgs, echos);
					},
					cps);
		}
		cps.wait();
		exit(EXIT_SUCCESS);
	});

	runtime.scheduleFromAnywhere(*client_producer);

	runtime.waitUntilFinished();

	return EXIT_FAILURE;
}