<?php

namespace AutoAdmin\Bundle\Content\Twig\Extension;

use AutoAdmin\Bundle\Content\Model\LocaleInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Provider\TranslationProvider;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class TranslationExtension extends AbstractExtension
{
    private EntityTranslator $entityTranslator;
    private TranslationProvider $translationProvider;

    public function __construct(
        EntityTranslator $translationService,
        TranslationProvider $translationProvider
    ) {
        $this->entityTranslator = $translationService;
        $this->translationProvider = $translationProvider;
    }

    /**
     * @return TwigFilter[]
     */
    public function getFilters(): array
    {
        return [
            // return entity translation for field and locale: aa_content_translate(content, 'title', 'en')
            new TwigFilter('aa_content_translate', [$this, 'translate']),
            // return static trans: aa_trans('key')
            // fallback on symfony |trans system if nothing is found
            new TwigFilter('aa_trans', [$this, 'staticTranslate'], ['is_safe' => ['html']]),
        ];
    }

    public function getFunctions()
    {
        return [
            // lock/unlock static text locale from template
            new TwigFunction('aa_trans_lock', [$this, 'staticTranslateLock']),
            new TwigFunction('aa_trans_unlock', [$this, 'staticTranslateUnlock']),
        ];
    }


    public function translate(TranslatableInterface $translatable, $field, $locale = null): ?string
    {
        return $this->entityTranslator->translate($translatable, $field, $locale);
    }

    public function staticTranslate(string $key, array $options = [], string $domain = 'messages', $locale = null)
    {
        return $this->translationProvider->translate($key, $domain, $options, $locale);
    }

    public function staticTranslateLock(mixed $locale): void
    {
        $this->translationProvider->lockLocale($locale);
    }

    public function staticTranslateUnlock(): void
    {
        $this->translationProvider->unlockLocale();
    }
}
