<?php
/**
 * Routing filter class
 * Implements the IFilter interface
 * @author Jerôme Brilland
 * @version 2.1
 * @copyright (c) 2012-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class RoutingFilter implements IFilter {

    /**
     * @param Request request Request object
     * @param Response response Response object
     * @access public
     */
    public function execute( Request $request, Response $response, FilterChain $filterchain ) {
        $dispatcher = FastRoute\simpleDispatcher( function( FastRoute\RouteCollector $r ) use ( $request, $response ) {
            IoC::resolve( 'eventmediator' )->trigger( 'before_route', [$r, $request, $response] ); 
            $routes = json_decode( file_get_contents( CONFIG_DIR . 'routes.json' ), true );
            foreach( $routes as $route ) {
                $r->addRoute( $route[0], $route[1], $route[2] );
            }
        });
        $httpMethod = $request->getMethod();
        // $uri = $request->getUri();
        // if ( false !== $pos = strpos( $uri, '?' ) ) {
        //     $uri = substr( $uri, 0, $pos );
        // }
        $uri = $request->getParameter( 'rt', '' );
        $uri = rawurldecode( $uri );

        $routeInfo = $dispatcher->dispatch( $httpMethod, $uri );
        
        switch ( $routeInfo[0] ) {
        case FastRoute\Dispatcher::NOT_FOUND:
            $request->setAttribute( 'controller', 'controllers\\ErrorController' );
            $request->setAttribute( 'action', '404' );
            IoC::resolve( 'eventmediator' )->trigger( 'page_not_found', [$routeInfo, $request, $response] );
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $allowedMethods = $routeInfo[1];
            $request->setAttribute( 'controller', 'controllers\\ErrorController' );
            $request->setAttribute( 'action', '405' );
            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];
            list( $controller, $action ) = explode( '@', $handler, 2 );
            $request->setAttribute( 'controller', $controller );
            $request->setAttribute( 'action', $action );
            foreach( $routeInfo[2] as $key => $value ) {
                $request->setAttribute( $key, $value );
            }
            break;
        }
        $filterchain->execute( $request, $response );
    }

}

