<?php namespace JsonApi;

class Response {

	/** @var array The list of encountered errors. **/
	private $errors = null;

	/** @var Interfaces\Resource The resource to show. **/
	private $resource;

	public static function createSuccess(Interfaces\Resource &$resource) {
		$response = new Response();
		$response->resource =& $resource;
		return $response;
	}

	public static function createErrors($errors) {
		$response = new Response();
		$response->errors = $errors;
		return $response;
	}

	public function getHeaders() {
		return [
			'Content-Type' => 'application/vnd.api+json'
		];
	}

	public function getBody() {

		# Errors
		if(!empty($this->errors)) {
			return json_encode([ 'errors' => $this->errors ]);
		}

		# Success
		if(!empty($this->resource)) {
			echo json_encode($this->resource);
			die;
		}
	}

	public function send() {

		# Send headers
		foreach($this->getHeaders() as $header => $value) {
			header("{$header}: {$value}");
		}

		# Send response
		echo $this->getBody();
		exit;
	}

}
