<?php

namespace AutoAdmin\Bundle\Content\Routing;

use Traversable;

class AutoRouterManager
{
    /**
     * @var array<ContentAutoRouterInterface>
     */
    protected array $routers;

    public function __construct(Traversable $guessers)
    {
        $this->routers = array_map([$this, 'addRouter'], iterator_to_array($guessers));
    }

    public function generate(ContentRouter $contentRouter, object $subject, ?string $route, array $parameters = [], array $options = [])
    {
        if ($subject === null) {
            return null;
        }

        $url = null;
        foreach ($this->routers as $router) {
            if ($router->supports($subject)) {
                $url = $router->buildUrl($contentRouter, $subject, $route, $parameters, $options);
                break;
            }
        }

        return $url;
    }

    protected function addRouter(ContentAutoRouterInterface $router): ContentAutoRouterInterface
    {
        return $router;
    }
}
