<?php
/**
 * Created by PhpStorm.
 * User: sale
 * Date: 16.10.17.
 * Time: 14.05
 */

//namespace Intellex\AutoPopulate\Generator;
namespace Intellex\Generator\Basic;

use Intellex\Generator\Core\GeneratorInterface;
use Intellex\Pixabay\Data\Image;
use Intellex\Pixabay\ImagesAPI;

class ImageGenerator implements GeneratorInterface {

	/** @const int Size of 180, for max image width. */
	const SIZE_180 = 180;

	/** @const int Size of 340, for max image width. */
	const SIZE_340 = 340;

	/** @const int Size of 640, for max image width. */
	const SIZE_640 = 640;

	/** @const int Size of 960 (default), for max image width. */
	const SIZE_960 = 960;

	/** @var int $size Max image width, in pixels. Possible values are SIZE_180, SIZE_340, SIZE_640 or SIZE_960 (default). */
	private $size;

	/** @var string API key for Pixabay. */
	private $apiKey;

	/** @var array Additional params for Pixabay API. */
	private $params;

	/** @var Image[] Cached images. */
	private static $cache = [ ];

	/**
	 * ImageGenerator constructor.
	 *
	 * @param  string $apiKey API key for Pixabay.
	 * @param int     $size   Max image width, in pixels. Possible values are SIZE_180, SIZE_340,
	 *                        SIZE_640 or SIZE_960 (default).
	 * @param array   $params Additional params for Pixabay API.
	 */
	public function __construct($apiKey, $size = 960, $params = [ ]) {
		$this->apiKey = $apiKey;
		$this->size = $size;
		$this->params = $params;
	}

	/**
	 * Get a URL to a random image from Pixabay.
	 *
	 * @return string Path to a random image on pixabay.
	 */
	public function generateValue() {
		$images = $this->fetch();

		$rand = rand(0, sizeof($images) - 1);
		return $this->getProperSize($images[$rand]);
	}

	/**
	 * Fetch the images from the API, but use cache to prevent flood exception on Pixabay API.
	 *
	 * @return Image[] The list of images.
	 */
	private function fetch() {

		// Check if exists
		$key = $this->getCacheKey();
		if (!key_exists($key, static::$cache)) {

			// Read from API
			$api = new ImagesAPI($this->apiKey);
			static::$cache[$key] = $api->fetch($this->params)->hits;
		}

		return static::$cache[$key];
	}

	/**
	 * Get the unique key which represents this API request.
	 *
	 * @return string The unique string representing the API request.
	 */
	private function getCacheKey() {
		return md5($this->apiKey . '-cache-' . serialize($this->params));
	}

	/**
	 * Get the specified size of the image.
	 *
	 * @param Image $image The image to get size from.
	 *
	 * @return string The URL to the requested size.
	 */
	public function getProperSize($image) {
		switch ($this->size) {
			case 180:
				return $image->getURLForSize180();
			case 340:
				return $image->getURLForSize340();
			case 640:
				return $image->getURLForSize640();
			case 960:
			default:
				return $image->getURLForSize960();
		}
	}

}
