<?php

namespace ProxiumWXfrm\Routing;

use Closure;
use ProxiumWXfrm\Http\HttpMethod;
use ProxiumWXfrm\Http\HttpNotFoundException;
use ProxiumWXfrm\Http\Request;

class Router {
    protected array $routes=[];

    public function __construct()
    {
        foreach (HttpMethod::cases() as $method) {
            //$this->routes[$method->value]=[];
            $this->routes[$method]=[];
        }
    }

    public function resolve(Request $request) {

        /*
        foreach ($this->routes[$request->method()] as $route) {
            if ($route->matches($request->uri())) {
                return $route;
            }
        }
        throw new HttpNotFoundException();
        */

        $uriConstruida='';
        $valoresUri=explode('/',$request->uri());

        $rutaEncontrada=NULL;

        foreach($valoresUri as $clave=>$valor){

            if($valor) $uriConstruida.='/'.$valor;

            foreach ($this->routes[$request->method()] as $route) {

                if ($route->matches($uriConstruida)) {

                    $rutaEncontrada=$route;
                    
                    if( $clave < count($valoresUri)-1 ) {
                        $parametros=array();
                        for($i=$clave+1;$i<count($valoresUri);$i++) $parametros[]=$valoresUri[$i];
                        $request->setQueryParams($parametros);
                    }

                }

            }
            
        }
        if($rutaEncontrada) {
            return $rutaEncontrada;
        }
        else throw new HttpNotFoundException();

    }

    protected function registerRoute(string $method,string $uri,Closure $action){
        $this->routes[$method][]=new Route($uri,$action);
    }

    public function get(string $uri,\Closure $action)  {
        $this->registerRoute(HttpMethod::GET,$uri,$action);
    }

    public function post(string $uri,\Closure $action)  {
        $this->registerRoute(HttpMethod::POST,$uri,$action);
    }

    public function put(string $uri,\Closure $action)  {
        $this->registerRoute(HttpMethod::PUT,$uri,$action);
    }

    public function patch(string $uri,\Closure $action)  {
        $this->registerRoute(HttpMethod::PATCH,$uri,$action);
    }

    public function delete(string $uri,\Closure $action)  {
        $this->registerRoute(HttpMethod::DELETE,$uri,$action);
    }

    
}