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

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

/**
 * Class Center
 * Centers the image into a predefined box, without any resizing.
 *
 * @package Intellex\Manicure\Plugin
 */
class Center 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) {

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

		// Handle X axis
		if ($this->dimension->width > $source->getWidth()) {
			$destination->x = ($this->dimension->width - $source->getWidth()) / 2;
		}

		// Handle Y axis
		if ($this->dimension->height > $source->getHeight()) {
			$destination->y = ($this->dimension->height - $source->getHeight()) / 2;
		}

		// No work to do?
		if ($destination->x === 0 && $destination->y === 0) {
			return new ImageDataSource($source->getData());
		}

		// Center
		return $this->resample($source, max($this->dimension->width, $origin->w), max($this->dimension->height, $origin->h), $origin, $destination);
	}
}