<?php

namespace AutoAdmin\Bundle\Admin\Twig\Extension;

use AutoAdmin\Bundle\Admin\Router\AdminRouter;
use AutoAdmin\Bundle\Content\Context\ContentContext;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Exception;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class FrontendBarExtension extends AbstractExtension
{
    public function __construct(
        private readonly Environment $twig,
        private readonly ContentContext $contentContext,
        private readonly SiteContextHelper $siteContextHelper,
        private readonly AdminRouter $adminRouter,
        private readonly TranslatorInterface $translator,
    )
    {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_admin_bar', [$this, 'getBar'], ['is_safe' => ['html'],]),
        ];
    }

    public function getBar(): string
    {
        $url = '/admin';
        $label = "Admin";

        try {
            $content = $this->contentContext->getMainContent();
            if (!empty($content) && !empty($content->getId())) {
                $url = $this->adminRouter->generate(
                    $this->contentContext->getMainContent(),
                    'update',
                    [
                        '_admin_locale' => $this->siteContextHelper->getLocale(),
                    ]
                );
                $label = $this->translator->trans('admin_bar.label', [], 'aa_admin');
            }
        } catch (Exception) {
        }

        return $this->twig->render('@AutoAdminAdmin/administrator/admin_bar.html.twig', [
            'admin_url' => $url,
            'admin_label' => $label,
        ]);
    }
}
