<?php


namespace AutoAdmin\Bundle\Content\Routing;


use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Model\ContentInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use AutoAdmin\Bundle\Content\Translation\LocaleResolver;
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 ?Request $request = null;

    public function __construct(
        protected ConfigManager $config,
        protected RouterInterface $router,
        protected SiteContextHelper $contextHelper,
        protected EntityTranslator $entityTranslator,
        protected LocaleResolver $localeResolver,
    ) {
    }

    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;
    }
}
