<?php
namespace Skeleton\Router;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Skeleton\Router;
use Skeleton\Request;

class RouterTwigExtention extends \Twig\Extension\AbstractExtension
{
    private ?Request $request = null;

    public function __construct(
        private Router $router,
        private ContainerInterface $contenaire
    ) {
    }

    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('path', [$this,'pathFor']),
            new \Twig\TwigFunction('getRouteName', [$this,'getRouteName']),
            new \Twig\TwigFunction('getRouteAttr', [$this,'getRouteAttr']),
            new \Twig\TwigFunction('getPost', [$this,'getPost']),
        ];
    }

    /**
     * Summary of pathFor
     * @param string $path
     * @param array<mixed> $params
     * @return string
     */
    public function pathFor(string $path, array $params = [])
    {
        return $this->router->generateUri($path, $params);
    }

    /**
     * @param array<mixed> $route
     */
    public function pathRoute(array $route) :string
    {
        return $this->router->generateUri($route['route'], $route['param']);
    }
    
    public function getRouteName() :string
    {
        return $this->router->getNameRoute();
    }

    /**
     * @return array<mixed>
     */
    public function getPost() :array
    {
        return $this->getRequest()->getParsedBody();
    }

    /**
     * @return array<mixed>
     */
    public function getRouteAttr() :array
    {
        return $this->getRequest()->getAttributes();
    }
    
    private function getRequest() :Request
    {
        // This code does not work if executed in __constructor
        return $this->request ?? ($this->request = new Request(
            $this->contenaire->get(ServerRequestInterface::class),
            $this->router
        )); // TODO: factorize with AbtractController Request creation
    }
}
