<?php namespace JsonApi;
class Relationships implements \JsonSerializable {

	/** @var array **/
	private $relationships = [];

	/**
	 * Add a relationship to the list.
	 *
	 * @param	Interfaces\Resource	$resource	The data of the relationship resource.
	 */
	public function add($name, Interfaces\Resource $resource, $multi = true) {
		if(!isset($this->relationships[$name])) {
			$this->relationships[$name] = $resource;

			if($multi) {
				$resource->getData()->write(new \JsonApi\Data\DataArray());
			}

		} else {
			throw new \Exception("Relationship `{$name}` already defined.");
		}
	}

	/**
	 * Get all relationships.
	 *
	 * @return	array	The list of all relationships, as name->Data pair.
	 */
	public function getRelationships() {
		return $this->relationships;
	}

	/**
	 * Get the data of a single relationship.
	 *
	 * @param	string	The name of the relationship.
	 *
	 * @return	Data	The data on the relationship.
	 */
	public function getRelation($name) {
		if(isset($name)) {
			return $this->relationships[$name];
		}

		throw new \Exception("Unknown relationship `{$name}`.");
	}

	public function setData($name, \JsonApi\Data\Dataitem $item) {
		$this->getRelation($name)->getData()->write($item);
	}

	public function addData($name, \JsonApi\Data\Dataitem $item) {
		$data = $this->getRelation($name)->getData()->read();
		if(!$data) {
			$data = new \JsonApi\Data\DataArray();
		}
		$data->add($item);

		$this->getRelation($name)->getData()->write($data);
	}

	public function jsonSerialize() {
		return $this->relationships;
	}

}
