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

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

/**
 * Resize the image, so that it fits into a defined dimension.
 */
class Scale 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 ($this->dimension->width == $this->dimension->width && $source->getHeight() == $this->dimension->height) {
			return new ImageDataSource($source->getData());
		}

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

		// Calculate the changes
		$scale = max($source->getWidth() / $this->dimension->width, $source->getHeight() / $this->dimension->height);
		$destination->w /= $scale;
		$destination->h /= $scale;

		return $this->resample($source, $destination->w, $destination->h, $origin, $destination);
	}

}