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

use Intellex\Manicure\Area;
use Intellex\Manicure\Dimension;
use Intellex\Manicure\Plugin\PluginInterface;
use Intellex\Manicure\Source\ImageDataSource;
use Intellex\Manicure\Source\SourceInterface;

/**
 * Resize the image, so it matches the supplied dimension.
 */
abstract class ResizeAbstract implements PluginInterface {

	/** @var Dimension The dimension of the resize image. */
	protected $dimension;

	/** @var int[] The background to fill, in format [ R (0-255), B (0-255), G  (0-255), A (0-127) ] */
	protected $background;

	/**
	 * Match constructor.
	 *
	 * @param int   $width      The width of the resized image.
	 * @param int   $height     The height of the resized image.
	 * @param int[] $background The background to fill, in format [ R (0-255), B (0-255), G
	 *                          (0-255), A (0-127) ]
	 */
	public function __construct($width, $height, $background = [ 0, 0, 0, 127 ]) {
		$this->dimension = new Dimension($width, $height);
		$this->background = $background;
	}

	/**
	 * Create an empty image.
	 *
	 * @return resource The created image.
	 */
	protected function createImage() {
		return imagecreatetruecolor($this->dimension->width, $this->dimension->height);
	}

	/**
	 * @param SourceInterface $source      The source to resample.
	 * @param int             $width       The total width of the image.
	 * @param int             $height      The total height of the image.
	 * @param Area            $origin      The origin from where to take the image.
	 * @param Area            $destination The destination to resample the image to.
	 * @param Area            $destination The destination to resample the image to.
	 *
	 * @return ImageDataSource The resampled image data source.
	 */
	protected function resample($source, $width, $height, Area $origin, Area $destination) {
		$result = imagecreatetruecolor($width, $height);

		// Transparency for images where destination does not cover complete image
		imagesavealpha($result, true);
		imagealphablending($result, false);
		imagefill($result, 0, 0, imagecolorallocatealpha($result, $this->background[0], $this->background[1], $this->background[2], $this->background[3]));

		// Resample
		imagecopyresampled(
			$result, $source->getData(),
			$destination->x, $destination->y,
			$origin->x, $origin->y,
			$destination->w, $destination->h,
			$origin->w, $origin->h
		);

		return new ImageDataSource($result);
	}

}
