<?php

namespace Planaday\Utility\DataGrouping;

use Error;

/**
 * @template T
 */
abstract class Enum {

	/**
	 * @return T[]
	 */
	public abstract static function getEnumArray():array;

	public static function from($value){
		if(!static::is($value)){
			throw new Error("Invalid enum value: $value");
		}

		return $value;
	}

	public static function tryFrom($value){
		return static::is($value) ? $value : null;
	}

	public static function cases(): array{
		return static::getEnumArray();
	}

	/**
	 * @param string $enumName
	 *
	 * @return T|null
	 */
	public static function get(string $enumName){
		return static::getEnumArray()[$enumName] ?? null;
	}

	/**
	 * @param T $enumValue
	 *
	 * @return false|int|string
	 */
	public static function getName($enumValue): false|int|string{
		return array_search($enumValue, static::getEnumArray());
	}

	/**
	 * @param string|int $name
	 *
	 * @return bool
	 */
	public static function isName(string|int $name):bool {
		return key_exists($name, static::getEnumArray());
	}

	/**
	 * @param T $value
	 *
	 * @return bool
	 */
	public static function is($value):bool {
		return in_array($value, static::getEnumArray());
	}
}