<?php

namespace IMATHUZH\Qfq\Core\Renderer\Element;

use IMATHUZH\Qfq\Core\Exception\RendererException;
use IMATHUZH\Qfq\Core\Helper\Support;
use CodeException;

/**
 * A renderer of a glyph icon.
 *
 * This is a stateless class implementing the singleton interface.
 */
class IconRenderer implements ElementRendererInterface, StaticElementRendererInterface {
    use RendererExceptionThrowerTrait;

    private static string $defaultIconFamily = '';

    /**
     * @param array $elementSpec
     * @param string $renderMode
     * @return string
     * @throws CodeException
     * @throws RendererException
     */
    public function render(array $elementSpec, string $renderMode = RENDER_MODE_HTML): string {
        return self::renderStatic($elementSpec, $renderMode);
    }

    /**
     * Renders an icon with specified parameters:
     *  + family      the family of icons to be used
     *  + name        the name of the icon within the family
     *  + tag         the tag element to render the icon; default is `i`
     *
     * @param array $elementSpec
     * @param string $renderMode
     * @return string
     * @throws CodeException
     * @throws RendererException
     */
    public static function renderStatic(array $elementSpec, string $renderMode = RENDER_MODE_HTML): string {
        // Only HMTL mode is supported
        if ($renderMode !== RENDER_MODE_HTML) return '';

        $tag = ($elementSpec[ICON_RENDERER_TAG] ?? null) ?: ICON_RENDERER_DEFAULT_TAG;
        $family = ($elementSpec[ICON_RENDERER_FAMILY] ?? null) ?: self::getDefaultIconFamily();
        $name = ($elementSpec[ICON_RENDERER_NAME] ?? null) or self::throwMissingArgument(self::class, ICON_RENDERER_NAME);

        $attrs = Support::doAttribute('class', "$family $family-$name");
        return "<$tag $attrs></$tag>";
    }

    /**
     * Returns the default icon family as configured in extension settings
     *
     * @return string
     */
    protected static function getDefaultIconFamily(): string {
        if (!self::$defaultIconFamily) {
            // @todo: get the default icon family from configuration
            self::$defaultIconFamily = ICON_RENDERER_DEFAULT_FAMILY;
        }
        return self::$defaultIconFamily;
    }
}
