<?php

namespace AutoAdmin\Bundle\Content\Routing;

use Traversable;

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

    protected array $refs = [];

    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 (array_key_exists($contentKey = $this->createKey($subject), $this->refs)) {
            return $this->refs[$contentKey];
        }

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

        if ($subject && !empty($contentKey)) {
            $this->refs[$contentKey] = $url;
        }

        return $url;
    }

    protected function createKey(object $content): string
    {
        return get_class($content).'#'.$content->getId();
    }

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