/* b01902062 藍ĉŒşç‘‹ */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "logger.h"
#include "xwrap.h"

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

typedef struct {
	pid_t pid;
	int   read;
	int   write;
} JudgeData;

typedef struct {
	long  score;
} PlayerData;

bool comb4 (Comp135* comp, int players[], long player_num) {
	for (int i = 3; i >= 0; i--) {
		if (players[i] + 1 <= player_num &&
			players[i] + 1 + (3 - i) <= player_num) {
			players[i]++;
			for (int j = i + 1; j < 4; j++) {
				players[j] = players[j - 1] + 1;
			}
			return true;
		}
	}
	return false;
}

int main (int argc, char* argv[]) {
	if (argc < 3) {
		fprintf (stderr, "Usage: %s judge_num player_num\n", argv[0]);
		return 1;
	}

	long judge_num, player_num;

	if (xatol (argv[1], &judge_num) < 0) {
		fprintf (stderr, "%s: `%s\' is not a number\n", argv[0], argv[1]);
		return 2;
	}
	if (judge_num < 0) {
		fprintf (stderr, "%s: judge_num must be a positive number\n", argv[0]);
		return 3;
	}

	if (xatol (argv[2], &player_num) < 0) {
		fprintf (stderr, "%s: `%s\' is not a number\n", argv[0], argv[2]);
		return 2;
	}
	if (player_num < 4) {
		fprintf (stderr, "%s: player_num must be greater than 4\n", argv[0]);
		return 3;
	}

	Comp135 comp_struct, *comp;
	comp = &comp_struct;

	comp135_init (comp, argv[0], false);

	JudgeData* jd = xmalloc (sizeof (JudgeData) * judge_num);
	PlayerData* pd = xmalloc (sizeof (PlayerData) * player_num);

	for (int i = 0; i < player_num; i++) {
		pd[i].score = 0;
	}
	for (int i = 0; i < judge_num; i++) {
		int fdr[2], fdw[2];
		if (pipe (fdr) < 0) {
			fprintf (stderr, "%s: pipe: %s\n", argv[0], strerror (errno));
			return 4;
		}
		if (pipe (fdw) < 0) {
			fprintf (stderr, "%s: pipe: %s\n", argv[0], strerror (errno));
			return 4;
		}

		jd[i].pid = fork ();
		if (jd[i].pid < 0) {
			fprintf (stderr, "%s: fork: %s\n", argv[0], strerror (errno));
			return 5;
		} else if (jd[i].pid > 0) {
			close (fdr[1]);
			close (fdw[0]);
		} else {
			close (fdr[0]);
			close (fdw[1]);
			char* myjudge = xgetres ("judge");
			execl (myjudge, "judge", xsprintf ("%d", i + 1), (char*)NULL);
			fprintf (stderr, "%s: execl: %s: %s\n", argv[0], myjudge, strerror (errno));
			_exit (1);
		}

		jd[i].read = fdr[0];
		jd[i].write = fdw[1];
		comp135_log (comp, "Judge %d created: PID = %u, read = %d, write = %d",
			i + 1, jd[i].pid, jd[i].read, jd[i].write);
	}

	int players[4] = {1, 2, 3, 4};
	do {

	} while (comb4 (comp, players, player_num));

	comp135_destroy (comp);

	return 0;
}