<?php
namespace Misuzu;

use Index\Http\HttpFx;
use Index\Http\HttpRequest;
use Index\Routing\IRouter;
use Index\Routing\IRouteHandler;
use Misuzu\URLs\IURLSource;
use Misuzu\URLs\URLInfo;
use Misuzu\URLs\URLRegistry;

class RoutingContext {
    private URLRegistry $urls;
    private HttpFx $router;

    public function __construct() {
        $this->urls = new URLRegistry;
        $this->router = new HttpFx;
        $this->router->use('/', fn($resp) => $resp->setPoweredBy('Misuzu'));
    }

    public function getURLs(): URLRegistry {
        return $this->urls;
    }

    public function getRouter(): IRouter {
        return $this->router;
    }

    public function registerDefaultErrorPages(): void {
        $this->router->addErrorHandler(400, fn($resp) => $resp->setContent(Template::renderRaw('errors.400')));
        $this->router->addErrorHandler(403, fn($resp) => $resp->setContent(Template::renderRaw('errors.403')));
        $this->router->addErrorHandler(404, fn($resp) => $resp->setContent(Template::renderRaw('errors.404')));
        $this->router->addErrorHandler(500, fn($resp) => $resp->setContent(file_get_contents(MSZ_TEMPLATES . '/500.html')));
        $this->router->addErrorHandler(503, fn($resp) => $resp->setContent(file_get_contents(MSZ_TEMPLATES . '/503.html')));
    }

    public static function registerSimpleErrorPages(IRouter $router, string $path): void {
        if($router instanceof HttpFx)
            $router->use($path, function() use($router) {
                $router->addErrorHandler(400, fn($resp) => $resp->setContent('HTTP 400'));
                $router->addErrorHandler(403, fn($resp) => $resp->setContent('HTTP 403'));
                $router->addErrorHandler(404, fn($resp) => $resp->setContent('HTTP 404'));
                $router->addErrorHandler(500, fn($resp) => $resp->setContent('HTTP 500'));
                $router->addErrorHandler(503, fn($resp) => $resp->setContent('HTTP 503'));
            });
    }

    public function register(IRouteHandler|IURLSource $handler): void {
        if($handler instanceof IRouteHandler)
            $this->router->register($handler);
        if($handler instanceof IURLSource)
            $handler->registerURLs($this->urls);
        URLInfo::handleAttributes($this->urls, $handler);
    }

    public function dispatch(?HttpRequest $request = null): void {
        $this->router->dispatch($request);
    }
}
