<?php namespace Intellex\Manicure\Source;

use Intellex\Filesystem\Exception\NotAnImageException;
use Intellex\Filesystem\File;

/**
 * A source from the local filesystem.
 */
class LocalSource implements SourceInterface {

	/** @var File The file containing the image. */
	protected $file;

	/** @var ImageDataSource The cached data source. */
	protected $data;

	/**
	 * LocalSource constructor.
	 *
	 * @param string $path The path to the source image.
	 */
	public function __construct($path) {
		$this->file = new File($path);
	}

	/** @inheritdoc */
	public function getData() {
		$this->load();
		return $this->data->getData();
	}

	/** @inheritdoc */
	public function getWidth() {
		$this->load();
		return $this->data->getWidth();
	}

	/** @inheritdoc */
	public function getHeight() {
		$this->load();
		return $this->data->getHeight();
	}

	/**
	 * Fill the data from the supplied path.
	 */
	protected function load() {
		if ($this->data === null) {
			$parser = $this->getCreateFunction();
			$this->data = new ImageDataSource($parser($this->file->getPath()));
		}
	}

	/**
	 * Get the create function to use for the file supplied.
	 *
	 * @return string The function to use, from the PHP GD library.
	 * @throws NotAnImageException
	 */
	private function getCreateFunction() {
		$mimetype = $this->file->getMimetype();
		switch ($mimetype) {
			case 'image/jpeg':
				return 'imageCreateFromJPEG';

			case 'image/png':
				return 'imageCreateFromPNG';

			case 'image/gif':
				return 'imageCreateFromGIF';

			default:
				throw new NotAnImageException($this->file->getPath());
		}
	}

}