<?php

namespace ProxiumWXfrm\Routing;

class Route {
    protected string $uri;
    protected \Closure $action;
    protected string $regex;
    protected array $parameters;

    public function __construct(string $uri,\Closure $action) {
        $this->uri=$uri;
        $this->action=$action;
        $this->regex=preg_replace("/\{([a-zA-Z]+)\}/","([a-zA-Z0-9]+)",$uri);
        $parameters=[];
        preg_match_all("/\{([a-zA-Z]+)\}/",$uri,$parameters);
        $this->parameters=$parameters[1];
    }

    public function uri()  {
        return $this->uri;
    }

    public function regex()  {
        return $this->regex;
    }

    public function action(): \Closure  {
        return $this->action;
        
    }

    public function matches($uri):bool  {
        return (bool)preg_match("#^$this->regex/?$#",$uri);
    }

    public function hasParameters():bool {
        return count($this->parameters);
    }

    public function parseParameters(string $uri) : array {
        preg_match("#^$this->regex$#",$uri,$arguments); // estrae los parametros
        return array_combine($this->parameters,array_slice($arguments,1)); // crea el vector clave-valor, al combinarlos uno a uno por posición dentro del vector
    }
}