<?php

namespace KupShop\KupShopBundle\Routing\Compiler;

use Symfony\Component\Routing\CompiledRoute;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCompiler;

class TranslatedRouteCompiler extends RouteCompiler
{
    public static function compile(Route $route): CompiledRoute
    {
        if (
            ($route->getOption('module') && !findModule($route->getOption('module')))
            || ($route->getOption('not_module') && findModule($route->getOption('not_module')))
        ) {
            $route->setCondition('false');
        }
        $path = $route->getPath();
        if ($route->getOption('translated_route') == 'simple') {
            $path = trim($path, '/');
            $path = explode(':', $path);
            $route->setPath('/'.translate($path[0], $path[1] ?? 'SEO_URL').'/');
        } else {
            $translatedPath = preg_replace_callback('/#(.+?)#/', function ($matches) {
                $matches = explode(':', $matches[1]);

                return translate($matches[0], $matches[1] ?? 'SEO_URL');
            }, $path);
            $route->setPath($translatedPath);
        }

        return parent::compile($route);
    }
}
