<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Service\Models;


class PersonCollection {

	/** Assoziative Arrays mit <Person-ID> => Wert @var array */
	protected array $persons = [];


	public function addPerson(PersonData $person): void {

		$oldPerson = $this->findPerson($person->getId());

		if ($oldPerson === FALSE) {

			$this->persons[$person->getId()] = $person;

		} else {

			// Merge two persons Attributes Arrays
			$oldPerson->setGroupValues($oldPerson->getGroupValues() + $person->getGroupValues());

		}

	}

	public function findPerson(int $id): PersonData|false {
		if (isset($this->persons[$id]) && $this->persons[$id] instanceof PersonData) {
			return $this->persons[$id];
		} else {
			return FALSE;
		}
	}

	/**
	 * @return PersonData[]
	 */
	public function getPersons(): array {
		return $this->persons;
	}

	/**
	 * @param PersonData[] $persons
	 * @return void
	 */
	public function setPersons(array $persons): void {
		$this->persons = $persons;
	}


	/**
	 * Gibt nur die in $pops übergebenen Keys aller Personen als Array zurück
	 *
	 * @param array $props
	 * @return array
	 */
	public function serializeOnly(array $props): array {

		$response = [];

		foreach ($this->getPersons() as $personId => $person) {
			$response[] = $person->serializeOnly($props);
		}

		return $response;

	}

	public function serializeAll(): array {
		$response = [];

		foreach ($this->getPersons() as $personId => $person) {
			$response[] = $person->serializeAll();
		}

		return $response;
	}
}
