<?php


namespace AutoAdmin\Bundle\Content\Routing;


use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\Context\SiteContext;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Model\ContentInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Routing\RouterInterface;

abstract class AbstractContentAutoRouter implements ContentAutoRouterInterface
{
    protected ConfigManager $config;
    protected RouterInterface $router;
    protected ?Request $request = null;
    protected EntityTranslator $entityTranslator;

    public function __construct(ConfigManager $config, RouterInterface $router, RequestStack $requestStack, SiteContext $siteContext, EntityTranslator $entityTranslator)
    {
        $this->config = $config;
        $this->router = $router;
        $this->request = $requestStack->getMainRequest();
        $this->entityTranslator = $entityTranslator;
    }

    protected function addAutoFilledParameters(string $routeName, array $parameters, ?ContentInterface $content): array
    {
        $routeConfig = $this->config->getRoute($routeName);
        $propertyAccessor = new PropertyAccessor();

        foreach ($routeConfig['autofill_parameters'] ?? [] as $key => $propertyPath) {
            if (isset($parameters['_locale']) && $parameters['_locale'] !== null) {
                $localeTranslation = (new Locale())->setCode($parameters['_locale']);
                if ($content instanceof TranslatableInterface) {
                    $propertyPath = str_replace('_tr.', '', $propertyPath);
                    $parameters[$key] = $this->entityTranslator->translate($content, $propertyPath, $localeTranslation);
                }
            } else {
                $propertyPath = str_replace('_tr.', 'currentTranslation.', $propertyPath);
                $parameters[$key] = $propertyAccessor->getValue($content, $propertyPath);
            }
        }

        return $parameters;
    }
}
