<?php
namespace Main\CompositePattern;

require_once 'AbstractWorker.php';

/*
 * Using the Standard PHP Library (SPL) class ArrayIterator
 */
use \ArrayIterator;

abstract class AbstractWorkGroup extends AbstractWorker
{	
	// Attributes
	private $_workers = [];
	
	// Constructor
	
	// Methods for properties
	// Getters and Setters
	public function GetIterator()
	{
		// Return an iterator that will recursively read down
		// the groups extracting all the Workers.
		return new WorkGroupIterator(array_values($this->_workers));
	}
	
	public function GetGroup()
	{
		// Return the group to allow
		// Add and Remove to be called.
		return $this;
	}
	
	public function GetNodeIterator()
	{
		// Return an iterator for reading through the
		// entries of the Workers array.
		return new ArrayIterator($this->_workers);
	}
	
	// Methods
	public function Add(AbstractWorker $worker)
	{
		$this->_workers[] = $worker;
	}
	
	public function AddWorkers(array $workers)
	{
		foreach($workers as $worker)
		{
			if($worker instanceof AbstractWorker)
			{
				$this->Add($worker);
			}
			else 
			{
				throw new Exception("Only workers can be added to WorkGroups");
			}
		}
	}
	
	public function Remove(AbstractWorker $worker)
	{
		$key = array_search($worker, $this->_workers, true);
		if($key !== false)
		{
			array_splice($this->_workers, $key, 1);  // Remove and normalize keys
		}	
	}
}
?>