<?php
namespace SabaiApps\Framework\Model\EntityCollection;

/**
 * DescendantEntitiesCountEntityCollectionDecorator class for decorating entity collections with descendant entity counts.
 * Adds functionality to calculate and assign the count of descendant entities for each entity in the collection.
 */
class DescendantEntitiesCountEntityCollectionDecorator extends AbstractEntityCollectionDecorator {

	protected $_entityName, $_descendantEntitiesCount;

	/**
	 * Constructor.
	 *
	 * @param string                   $entityName Name of the descendant entity.
	 * @param AbstractEntityCollection $collection Entity collection to decorate.
	 */
	public function __construct( $entityName, AbstractEntityCollection $collection ) {
		parent::__construct( $collection );
		$this->_entityName = $entityName;
	}

	/**
	 * Rewinds the collection and calculates descendant entity counts.
	 */
	#[\ReturnTypeWillChange]
	public function rewind() {
		$this->_collection->rewind();
		if ( ! isset( $this->_descendantEntitiesCount ) ) {
			$this->_descendantEntitiesCount = array();
			if ( $this->_collection->count() > 0 ) {
				$parent_ids                     = $this->_collection->getAllIds();
				$this->_descendantEntitiesCount = $this->_model->getRepository( $this->_entityName )->countDescendantsByIds( $parent_ids );
				$this->_collection->rewind();
			}
		}
	}

	/**
	 * Gets the current entity and assigns its descendant entity count.
	 *
	 * @return mixed Current entity with descendant entity count.
	 */
	#[\ReturnTypeWillChange]
	public function current() {
		$current = $this->_collection->current();
		$id      = $current->id;
		$current->setDescendantsCount( isset( $this->_descendantEntitiesCount[ $id ] ) ? $this->_descendantEntitiesCount[ $id ] : 0 );

		return $current;
	}
}
