<?php declare(strict_types=1);

use FastRoute\RouteCollector;
use Middlewares\Utils\Dispatcher;
use Psr\Http\Message\ResponseFactoryInterface;
use Rescraft\Plugin\HTTP\FallbackHandler;
use Rescraft\Plugin\HTTP\QueueRequestHandler;
use Rescraft\Plugin\HTTP\Request;
use Rescraft\Plugin\HTTP\Router;
use Rescraft\Plugin\HTTP\RouterMiddleware;
use function FastRoute\simpleDispatcher;

ini_set("display_errors", "1");
error_reporting(E_ALL);

require(__DIR__ . "/../vendor/autoload.php");

// creating the request object is non-negotiable for the web application
$request = Request::fromGlobals();

// dispatcher also useful to the web app
//$dispatcher = simpleDispatcher(function(RouteCollector $r) {
//    $r->addRoute('POST', '/users', 'get_all_users_handler');
//});
//
//$routerMiddleware = new RouterMiddleware(new Router($dispatcher));
//
//$queueRequestHandler = new QueueRequestHandler(new FallbackHandler());
//$queueRequestHandler->add($routerMiddleware);
//$queueRequestHandler->handle($request);


//Create the router dispatcher
$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/hello/{name}', function (Request $request) {
        //The route parameters are stored as attributes
        $name = $request->getAttribute('name', "anonymous");

        //You can echo the output (it will be captured and written into the body)
        echo sprintf('Hello %s', $name);

        //Or return a string
        return sprintf('Hello %s', $name);

        //Or return a response
        //return new Response();
    });
});

class ResponseFactory implements ResponseFactoryInterface {
    public function createResponse(int $code = 200, string $reasonPhrase = ''): \Psr\Http\Message\ResponseInterface
    {
        // TODO: Implement createResponse() method.
    }
}

$dispatcher = new Dispatcher([
    new Middlewares\FastRoute($dispatcher, new ResponseFactory()),
    new Middlewares\RequestHandler()
]);

$response = $dispatcher->dispatch($request);