<?php
namespace Engine\Mvc\Response\Components;

/**
 * The standard headers response
 * @author Lucian Sirbu
 */
class Headers
{
	/**
	 * Internal data
	 * @var array
	 */
	private $headers = [];

	/**
	 * Internal json data
	 * @var \stdClass
	 */
	private $json = null;

	/**
	 * Create the headers response
	 * @param array $headers
	 */
	public function __construct($headers)
	{
		$this->headers = $headers;
	}

	/**
	 * Set the internal X-JSON object
	 * @param $json
	 */
	public function setJson($json)
	{
		$this->json = $json;
	}

	/**
	 * Get the internal X-JSON object
	 * @return \stdClass
	 */
	public function getJson()
	{
		if ($this->json===null) {
			$this->json = new \stdClass();
		}

		return $this->json;
	}

	/**
	 * Append to the internal headers list
	 * @param string $name
	 * @param string $value
	 */
	public function append($name, $value)
	{
		$this->headers[] = sprintf("%s: %s", $name, $value);
	}

	/**
	 * Attach  messages to headers
	 * @param \App\MessagesCollector $msgs
	 */
	public function loadMessages(\App\MessagesCollector $msgs)
	{
		$jsonMessages = $this->getJson();
		if (property_exists($jsonMessages, 'messages')) {
			$displayedMessages = (array)$jsonMessages->messages;
		} else {
			$displayedMessages = [];
		}
		foreach($msgs->getMessages() as $message) {
			$displayedMessages[] = ['type' => $message->getType(), 'message' => $message->getText()];
		}

		$jsonMessages->messages = $displayedMessages;
		$this->setJson($jsonMessages);
	}

	/**
	 * Get all headers
	 * @return multitype:string
	 */
	public function getAll()
	{
		$headers = [];
		foreach ($this->headers as $header) {
			$headers[] = $header;
		}

		// TODO: in PHP 5.4 we could check if an objecty is empty by doing empty() or typecast to array, or typecast to bool
		// @see http://stackoverflow.com/questions/9412126/how-to-check-if-an-object-is-empty-in-php
		if ($this->json!==null && $this->json!=new \stdClass()) {
			$headers[] = sprintf("X-JSON: %s", json_encode((object)$this->json));
		}

		return $headers;
	}
}
