<?php namespace Intellex\Manicure\Plugin\Resize;

use Intellex\Manicure\Area;
use Intellex\Manicure\Source\ImageDataSource;
use Intellex\Manicure\Source\SourceInterface;

/**
 * Resize the image, so it matches the supplied dimension.
 */
class Match extends ResizeAbstract {

	/** @inheritdoc */
	public function apply(SourceInterface $source) {
		return $this->resize($source);
	}

	/**
	 * Resize the image.
	 *
	 * @param SourceInterface $source The source on which to apply the manipulation.
	 *
	 * @return SourceInterface The reworked source.
	 */
	public function resize(SourceInterface $source) {

		// Is there something to change
		if ($source->getWidth() == $this->dimension->width && $source->getHeight() == $this->dimension->height) {
			return new ImageDataSource($source->getData());
		}

		// Initialize
		$destination = new Area(0, 0, $this->dimension->width, $this->dimension->height);
		$origin = new Area(0, 0, $source->getWidth(), $source->getHeight());

		// Calculate the changes
		$ratio = ($this->dimension->width / $this->dimension->height) / ($source->getWidth() / $source->getHeight());
		if ($ratio < 1) {
			$origin->w *= $ratio;
			$origin->x = ($source->getWidth() - $origin->w) / 2;
		} else if ($ratio > 1) {
			$origin->h /= $ratio;
			$origin->y = ($source->getHeight() - $origin->h) / 2;
		}

		return $this->resample($source, $this->dimension->width, $this->dimension->height, $origin, $destination);
	}

}