<?php

/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

namespace Resursbank\MerchantApi\EventListener\KernelRequest;

use LogicException;
use Resursbank\MerchantApi\Util\Log;
use Resursbank\MerchantApi\Util\Translator;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Throwable;
use Twig\Environment;
use Twig\TwigFilter as MainTwigFilter;

/**
 * Add custom Twig filter to access Ecom translation library from templates.
 */
class TwigTranslations
{
    public function __construct(
        private readonly Environment $twig
    ) {
    }

    public function exec(RequestEvent $event): void
    {
        $translateFilter = new MainTwigFilter('ecom_trans', function ($text) {
            return Translator::translate($text);
        });

        try {
            $this->twig->addFilter($translateFilter);
        } catch (LogicException $error) {
            // Some requests will cause this to execute twice, which causes a
            // problem because the same filter cannot be added twice.
            // Attempting to get a list of assigned filters seems to cause
            // filters to be collected again, meaning the issue will then be
            // present on all requests. For now, it seems the only way to avoid
            // the problem is to ignore LogicException since they will naturally
            // occur on some requests (observed when saving config).
        } catch (Throwable $error) {
            // @todo Add flash message for back end.
            Log::error($error);
        }
    }
}
