<?php namespace Puzzle;
class Canvas {

	/** @var string The background of the canvas. **/
	private $background = null;

	/** @var array The images in the canvas. **/
	private $images = [];

	/**
	 * Initialize the canvas.
	 *
	 * @param	string	$background	The background color of the canvas.
	 */
	public function __construct(\Color\Color $background = null) {
		$this->background = $background;
	}

	/**
	 * Add an image into the canvas.
	 *
	 * @param	Image	$image	The image to add.
	 *
	 * @return	Color	Self, for chaining.
	 */
	public function add(Image $image) {
		$this->images[] = $image;
	}

	/**
	 * Render the canvas to a image.
	 *
	 * @param	int		$width		The width of the canvas, in pixels.
	 * @param	int		$height		The height of the canvas, in pixels.
	 */
	public function render($width, $height) {

		# Create canvas
		$canvas = imagecreatetruecolor($width, $height);
		imagefilledrectangle($canvas, 0, 0, $width, $height, $this->background->allocateColor($canvas));

		# Draw images
		$images = self::sort($this->images);
		foreach($images as $image) {

			# Load
			$img = imagecreatefromjpeg($image->getSource());
			list($w, $h) = getimagesize($image->getSource());

			# Put
			imagecopyresampled($canvas, $img, $width * $image->getX(), $height * $image->getY(), 0, 0, $w, $h, $w, $h);
		}

		return $canvas;
	}

	/**
	 * Sort the images by their order.
	 *
	 * @param	array	$images	The images to sort.
	 *
	 * @return	The sorted list of images.
	 */
	public static function sort($images) {

		# Sort the images
		$sorted = [];
		foreach($images as $image) {
			$sorted[$image->getOrder()][] = $image;
		}
		ksort($sorted);

		# Flat
		$images = [];
		foreach($sorted as $array) {
			foreach($array as $image) {
				$images[] = $image;
			}
		}

		return $images;
	}

}
