<?php

class ImageHelper extends AppHelper {

	/** @var array Other helpers used by FormHelper. */
	public $helpers = [ 'Html' ];

	/**
	 * Render an image.
	 *
	 * @param object $image The image, as stored in database.
	 * @param boolean $params The additional params for the HTML tag.
	 *
	 * @return string The URL to the image.
	 */
	public function url($image, $absolute = false) {
		return ($absolute ? FRONT_BASE_URL : null) . $image['file'];
	}

	/**
	 * Render an image from database.
	 *
	 * @param object $image The image, as stored in database.
	 * @param boolean $params The additional params for the HTML tag.
	 * @param mixed $params The additional params for the HTML tag.
	 *
	 * @return string The img HTML tag.
	 */
	public function draw($image, $absolute = false, $params = []) {

		# Make sure we have the image
		if(!$image || !is_readable(preg_replace('~\?.*$~', '', WWW_ROOT . $image['file']))) {
			$image = [
				'file' =>  '/img/no-image.png',
				'filename' => null,
				'alt' => null
			];
		}

		# Generate a proper link
		$image['file'] = $this->url($image, $absolute);

		# Set the parameters
		$params = array_merge($params, [
			'title' => $image['filename'],
			'alt' => $image['alt'],
			'fullBase' => $absolute,
		]);

		# Zoom
		if(!empty($params['zoom'])) {
			$params['data-zoom'] = $params['zoom'];
		}

		return $this->Html->image($image['file'], $params);
	}

	public function thumbnailURL($image, $width, $height, $absolute = false) {
		$image['file'] = $image['file'] . '?' . http_build_query(compact('width', 'height'));
		return $this->url($image);
	}

	public function thumbnail($image, $width, $height, $zoom = false, $params = []) {
		$image['file'] = $this->thumbnailURL($image, $width, $width, !empty($params['baseUrl']));
		$params['rel'] = $zoom;
		return $this->draw($image, $params);
	}

	/**
	 * Check if the image exists.
	 *
	 * @param array $image The image to check.
	 *
	 * @return boolean True if image exists and can be readable, false otherwise.
	 */
	public function exists($image) {
		return !$image || !is_readable(preg_replace('~\?.*$~', '', WWW_ROOT . $image['file']));
	}

}
