<?php

namespace AutoAdmin\Bundle\Admin\Twig\Extension;

use AutoAdmin\Bundle\Content\Context\SiteContext;
use Doctrine\Common\Collections\ArrayCollection;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class LocaleExtension extends AbstractExtension
{
    private array $locales;
    private SiteContext $siteContext;

    public function __construct(array $locales, SiteContext $siteContext)
    {
        $this->locales = $locales;
        $this->siteContext = $siteContext;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_admin_locale_switcher', [$this, 'getSwitcher']),
            new TwigFunction('aa_lang_site_locales', [$this, 'getLocales']),
        ];
    }

    public function getLocales(): array
    {
        /** @var ArrayCollection $locales */
        $locales = $this->siteContext->getDomain()->getLocales();

        return $locales->toArray();
    }

    public function getSwitcher(): array
    {
        $currentLocale = $this->siteContext->getLocale();
        /** @var ArrayCollection $locales */
        $locales = $this->siteContext->getDomain()->getLocales();

        return [
            'current' => $this->siteContext->getLocale(),
            'locales' => array_filter($locales->toArray(), function ($el) use ($currentLocale) {
                return $el != $currentLocale;
            }),
        ];
    }
}
