#ifndef COLLECTIVE_SCHEDULER_HPP
#define COLLECTIVE_SCHEDULER_HPP

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cmath>
#include "task.hpp"

class CollectiveScheduler {
	private:
		int levels;

	public:
		CollectiveScheduler(int lvls) : levels(lvls) {}

		void execute(Task* task) {
		pid_t root= getpid();

		for (int i=0; i<levels; i++) {
			fork();
		}

		if(getpid()!=root) {
			int worker_id = getpid() %root;
			int worker_count = std::pow(2,levels) -1;

			if(task !=nullptr) {
				task->execute_task(worker_id,worker_count);
			}
		}

		int status;
		while (true) {
			pid_t finished = waitpid(-1, &status, 0);
			if(finished == -1 && errno == ECHILD) {
				break;
			}
		}

		if (getpid() !=root) {
			_exit(0);
		}
	}
};

#endif
			
		
