<?php
namespace Skeleton\Router;

use Helpers\Log\LogSysteme;

use Mezzio\Router\FastRouteRouter;
use Psr\Http\Message\ServerRequestInterface as Request;
use Mezzio\Router\Route;
use Helpers\Session\ParseBase1;
use Mezzio\Router\RouteResult;

// @phpstan-ignore-next-line
class FastRouteRouterDev extends FastRouteRouter
{

    /** @var array<string> */
    private array $listRouteName;

    public function __construct()
    {
        parent::__construct(null, null, [
            FastRouteRouter::CONFIG_CACHE_ENABLED => true,
            FastRouteRouter::CONFIG_CACHE_FILE => (new ParseBase1())->getRep()->tmp.LogSysteme::getServerName().'.ZendRoute'.$_SESSION['cache'],
        ]);
        $this->listRouteName = [];
    }

    public function addRoute(Route $route) : void
    {
        $this->listRouteName[] = $route->getName();
        parent::addRoute($route);
    }

    private function injectRoutes() : void
    {
        $method = new \ReflectionMethod(FastRouteRouter::class, 'injectRoutes');
        $method->setAccessible(true);

        if (($_SESSION['DEV_ROUTE_CACHE_TTL'] ?? null) != md5(join('', $this->listRouteName))) {
            $class = new \ReflectionClass(FastRouteRouter::class);
                $property = $class->getProperty('hasCache');
            $property->setAccessible(true);
            $property->setValue($this, false);

            //$this->hasCache = false;

            $_SESSION['DEV_ROUTE_CACHE_TTL'] = md5(join('', $this->listRouteName));
        }
        $method->invoke($this);
    }

    public function match(Request $request) :RouteResult
    {
        // Inject any pending routes
        $this->injectRoutes();

        return parent::match($request);
    }
}
