<?php
namespace App\Utils\BaseParser\Structure\StructureParser\Types;

/**
 * Base structure for the document relations data
 * @author Lucian
 */
abstract class Relations extends \App\Utils\BaseParser\Structure\StructureParser\Types\BaseAbstract implements \App\Utils\BaseParser\NoParamsConstructorInterface
{
	/**
	 * The internal list of relations
	 * @var array:\App\Utils\BaseParser\Structure\StructureParser\Types\Relation
	 */
	public $relations = [];

	/**
	 * Forced by the interface.
	 */
	public function __construct()
	{ }

	public function appendRelation(\App\Utils\BaseParser\Structure\StructureParser\Types\Relation $relation)
	{
		$this->relations[] = $relation;
	}

	public function filter($type)
	{
		$ret = new static();
		foreach ($this->relations as $rel) {
			/* @var $rel \App\Utils\BaseParser\Structure\StructureParser\Types\Relation */

			if ($rel->relationType==$type) {
				$ret->appendRelation($rel);
			}
		}

		return $ret;
	}

	/**
	 * Get the first relation in the internal list
	 * @return \App\Utils\BaseParser\Structure\StructureParser\Types\Relation
	 */
	public function first()
	{
		return $this->relations[0];
	}

	/**
	 * Remove a relation
	 *
	 * @param \App\Utils\BaseParser\Structure\StructureParser\Types\Relation $relation
	 * @return \App\Utils\BaseParser\Structure\StructureParser\Types\Relation
	 */
	public function remove(\App\Utils\BaseParser\Structure\StructureParser\Types\Relation $relation)
	{
		$removed = false;
		foreach ($this->relations as $k=>$rel) {
			if ($rel === $relation) {
				$this->relations[$k] = null;
				$removed = true;
			}
		}

		if (!$removed) {
			throw new \App\Utils\BaseParser\Structure\StructureParser\Types\Exception\Exception("No relation was removed");
		}

		$this->relations = array_filter($this->relations);

		return $this;
	}
}
