<?php

namespace onespace\tools\enum\base;

/**
 * Trait for some common helpful methods used by unbacked enums.
 *
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

trait UnbackedHelper {
    /**
     * An unbacked enum required an id. This method should return and integer ID for each entry.
     *
     * @return  int|string
     *
     * @access  public
     */
    abstract public function id(): int|string;

    /**
     * An unbacked enum requires a name which returns a basic human readable word or phrase
     * for the enum.
     *
     * @return  string
     *
     * @access  public
     */
    abstract public function name(): string;

    /**
     * Returns a list of all the enum names indexed by id and listing each name.
     *
     * @return  array
     *
     * @static
     * @access  public
     */
    public static function list(): array {
        $list = [];
        foreach (self::cases() as $item) {
            $list[$item->id()] = $item->name();
        }
        return $list;
    }

    /**
     * Get the name value of an enum from an ID.
     *
     * @param   int $id The ID to search for.
     *
     * @return  string
     *
     * @static
     * @access  public
     */
    public static function from(int $id): string {
        return self::list()[$id];
    }

    /**
     * Returns a list of all the enums indexed by id and listing each name.
     *
     * @return  array
     *
     * @static
     * @access  public
     */
    public static function enumList(): array {
        $list = [];
        foreach (self::cases() as $item) {
            $list[$item->id()] = $item;
        }
        return $list;
    }

    /**
     * Get the enum from an ID.
     *
     * @param   int $id The ID to search for.
     *
     * @return  static
     *
     * @static
     * @access  public
     */
    public static function enumFrom(int $id): static {
        return self::enumList()[$id];
    }

    /**
     * Formatted list as typically used by PrimeReact
     *
     * @return  array
     *
     * @static
     * @access  public
     */
    public static function formattedList(): array {
        $data = [];
        foreach (self::cases() as $enum) {
            $data[] = [
                'id' => $enum->id(),
                'name' => $enum->name(),
            ];
        }

        return $data;
    }
}
