<?php
namespace App\Smarty\Functions;

/**
 * Theme-related functions
 * @author Lucian Sirbu
 */
class Theme
{
	static public $uniqueColors = [];
	static public $associatedUniqueColors = [];

	static public function pickUniqueColor($params, $smarty)
	{
		$cycles = 	($params['cycles']?:6);
		$theme = 	($params['theme']?:'light');

		if (!array_key_exists($theme, static::$uniqueColors)) {
			static::$uniqueColors[$theme] = [];
		}
		if (!array_key_exists($theme, static::$associatedUniqueColors)) {
			static::$associatedUniqueColors[$theme] = [];
		}

		if (!static::$uniqueColors[$theme][$cycles]) {
			switch ($theme) {
				case 'light':
					static::initializeColorTheme($theme, $cycles, 0, 33, 85);
				break;
				case 'dark':
					static::initializeColorTheme($theme, $cycles, 0, 66, 25);
				break;
				default:
					throw new \Exception("Unknown color theme specified: {$theme}");
			}
		}

		$key = $params['key'];
		if (array_key_exists($key, static::$associatedUniqueColors[$theme])) {
			$colorIdx = static::$associatedUniqueColors[$theme][$key];
			return static::$uniqueColors[$theme][$cycles][$colorIdx];
		}

		$lastPick = end(static::$associatedUniqueColors[$theme]);
		$step = round(0.3*$cycles);

		$colorIdx = ($lastPick + $step - 1) % $cycles;
		if ($colorIdx==$lastPick) {
			$colorIdx = ($colorIdx + 1) % $cycles;
		}

		static::$associatedUniqueColors[$theme][$key] = $colorIdx;
		return static::$uniqueColors[$theme][$cycles][$colorIdx];
	}

	static protected function initializeColorTheme($theme, $cycles, $hue, $saturation, $lightness)
	{
		for ($i=0; $i<$cycles; $i++) {
			$currentHue = ($hue + round(($i/$cycles) * 360)) % 360;
			$color = sprintf("hsl(%d, %d%%, %d%%)", $currentHue, $saturation, $lightness);
			static::$uniqueColors[$theme][$cycles][]= $color;
		}
	}
}
