package com.zurrox.zybot.hitbox.workers;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A factory class for creating Workers when they are required.
 */
public class WorkerFactory {
    TaskQueue queue;
    List<Worker> workers = new CopyOnWriteArrayList<>();

    public WorkerFactory(TaskQueue queue) {
        this.queue = queue;
        newWorker(); //Initialize the factory with one worker.
    }

    /**
     * Starts a worker which currently is not running or creates one if none are available.
     */
    public void newWorker() {
        for (Worker worker : workers) {
            if (!worker.isRunning()) {
                worker.setRunning(true);
                worker.run();
                return;
            }
        }

        Worker worker = new Worker(queue);
        workers.add(worker);
        worker.start();
    }

    /**
     * Stop the last worker if there is at least one running.
     */
    public void stopWorker() {
        if (workers.size() > 2) workers.get(workers.size()).setRunning(false);
    }

    /**
     * Removes excess workers from the list of workers.
     */
    public void cleanupWorkers() {
        long inactiveWorkers;
        inactiveWorkers = workers.stream().filter(w -> !w.isRunning()).count();

        for (int i = 1; i < inactiveWorkers; i++) workers.remove(workers.size());
    }
}