<?php

namespace Plainwork\HttpWordPress;

use Plainwork\Http\Request;
use Plainwork\Http\Response;
use Plainwork\Http\Server;

class WordPressServer
{
    public $server = Server::class;

    public function handleWpRestRequest(
        \WP_REST_Request $wpRestRequest,
        string $wpRouteNamespace,
        string $ourRouteNamespace
    ) {
        $request = $this->buildRequest($wpRestRequest, $wpRouteNamespace, $ourRouteNamespace);

        $ret = $this->server->handle($request);
        if ($ret instanceof Response) {
            $ret = new \WP_REST_Response($ret->getBody(), $ret->getStatusCode());
        }

        return $ret;
    }

    private function buildRequest(
        \WP_REST_Request $wpRestRequest,
        string $wpRouteNamespace,
        string $ourRouteNamespace
    ): Request {
        $request = new Request();

        $request = $request->withRequestMethod($wpRestRequest->get_method());

        $queryParams = $wpRestRequest->get_query_params();
        $request = $request->withQueryParams($queryParams);

        $routeParams = $wpRestRequest->get_url_params();
        $request = $request->withRouteParams($routeParams);

        $headers = $wpRestRequest->get_headers();
        $request = $request->withHeaders($headers);

        $wpRoute = $wpRestRequest->get_route();
        $wpRoute = ltrim($wpRoute, '/');
        $ourPath = $ourRouteNamespace . substr($wpRoute, strlen($wpRouteNamespace));
        $ourPath = ltrim($ourPath, '/');

        $request = $request->withPath($ourPath);

    // try body params
        $isJson = wp_is_json_request();
        $values = $isJson ? $wpRestRequest->get_json_params() : $wpRestRequest->get_body_params();
        if (!$values) {
            $body = $wpRestRequest->get_body();
            parse_str($body, $values);
        }

        if (is_array($values)) {
            $request = $request->withParsedBody($values);
        }

        return $request;
    }
}
