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

use SabaiApps\Framework\Model\Model;
use SabaiApps\Framework\Model\AbstractEntity;

/**
 * AssocEntityCollection class for managing collections of associated entities.
 * Provides methods for iterating and accessing associated entities.
 */
abstract class AssocEntityCollection extends AbstractEntityCollection {

	protected $_assoc, $_emptyEntity, $_count;

	/**
	 * Constructor.
	 *
	 * @param string         $name Name of the entity.
	 * @param array          $assoc Array of associated entities.
	 * @param AbstractEntity $emptyEntity Empty entity instance for cloning.
	 * @param Model          $model Model instance.
	 */
	public function __construct( $name, array $assoc, AbstractEntity $emptyEntity, Model $model ) {
		parent::__construct( $model, $name );
		$this->_assoc       = $assoc;
		$this->_emptyEntity = $emptyEntity;
	}

	/**
	 * Counts the number of associated entities.
	 *
	 * @return int Number of associated entities.
	 */
	#[\ReturnTypeWillChange]
	public function count() {
		return count( $this->_assoc );
	}

	/**
	 * Checks if the current entity is valid.
	 *
	 * @return bool True if valid, false otherwise.
	 */
	#[\ReturnTypeWillChange]
	public function valid() {
		return isset( $this->_assoc[ $this->_key ] );
	}

	/**
	 * Gets the current entity by index.
	 *
	 * @param int $index Index of the entity.
	 * @return AbstractEntity Current entity.
	 */
	public function getCurrent( $index ) {
		$entity = clone $this->_emptyEntity;
		$this->_loadRow( $entity, $this->_assoc[ $index ] );

		return $entity;
	}

	/**
	 * Abstract method for loading a row into an entity.
	 *
	 * @param AbstractEntity $entity Entity instance.
	 * @param array          $row Row data.
	 */
	abstract protected function _loadRow( AbstractEntity $entity, array $row );
}
