<?php

namespace engine\skin\TwigAddons;

use engine\skin\BaseSkin;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class SkinTwigExtension
    extends AbstractExtension
{
    public function __construct(protected BaseSkin $skin) {}

    public function getFunctions() {
        return [
            new TwigFunction('svg', fn($name) => $this->skin->getSVG($name),
                ['is_safe' => ['html']]),

            new TwigFunction('svgInPlace', fn($name) => $this->skin->getSVG($name, in_place: true),
                ['is_safe' => ['html']]),

            new TwigFunction('svgPreload', function(...$icons) {
                foreach ($icons as $icon)
                    $this->skin->preloadSVG($icon);
                return null;
            }),

            new TwigFunction('bc', fn(...$args) => $this->skin->renderBreadCrumbs(...$args),
                ['is_safe' => ['html']]),

            new TwigFunction('pageNav', fn(...$args) => $this->skin->renderPageNav(...$args),
                ['is_safe' => ['html']]),

            new TwigFunction('csrf', function($value) {
                global $globalContext;
                return $globalContext->requestHandler->getCSRF($value);
            })
        ];
    }

    public function getFilters() {
        return [
            new TwigFilter('lang', function($key, array $args = []) {
                array_walk($args, function(&$item, $key) {
                    $item = htmlescape($item);
                });
                array_unshift($args, $key);
                return $this->skin->strings->get(...$args);
            }, ['is_variadic' => true]),

            new TwigFilter('hl', function($s, $keywords) {
                return highlightSubstring($s, $keywords);
            }),

            new TwigFilter('plural', function($text, array $args = []) {
                array_unshift($args, $text);
                return $this->skin->strings->num(...$args);
            }, ['is_variadic' => true]),
        ];
    }
}
