<?php

/*
 * Copyright 2010 Google Inc.
 * Copyright 2015 www.wpcloudplugins.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

if (!class_exists('SODOneDrive_Client')) {
    require_once dirname(__FILE__).'/../autoload.php';
}

/**
 * This class implements the RESTful transport of apiServiceRequest()'s.
 */
class SODOneDrive_Http_REST
{
    /**
     * Executes a SODOneDrive_Http_Request and (if applicable) automatically retries
     * when errors occur.
     *
     * @return array decoded result
     *
     * @throws SODOneDrive_Service_Exception on server side error (ie: not authenticated,
     *                                       invalid or malformed post body, invalid url)
     */
    public static function execute(SODOneDrive_Client $client, SODOneDrive_Http_Request $req)
    {
        $runner = new SODOneDrive_Task_Runner(
            $client,
            sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
            [__CLASS__, 'doExecute'],
            [$client, $req]
        );

        return $runner->run();
    }

    /**
     * Executes a SODOneDrive_Http_Request.
     *
     * @return array decoded result
     *
     * @throws SODOneDrive_Service_Exception on server side error (ie: not authenticated,
     *                                       invalid or malformed post body, invalid url)
     */
    public static function doExecute(SODOneDrive_Client $client, SODOneDrive_Http_Request $req)
    {
        $httpRequest = $client->getIo()->makeRequest($req);
        $httpRequest->setExpectedClass($req->getExpectedClass());

        return self::decodeHttpResponse($httpRequest, $client);
    }

    /**
     * Decode an HTTP Response.
     *
     * @static
     *
     * @param SODOneDrive_Http_Request $response the http response to be decoded
     *
     * @return null|mixed
     *
     * @throws SODOneDrive_Service_Exception
     */
    public static function decodeHttpResponse($response, ?SODOneDrive_Client $client = null)
    {
        $code = $response->getResponseHttpCode();
        $body = $response->getResponseBody();
        $decoded = null;

        if (intval($code) >= 300 && (302 != intval($code)) && (301 != intval($code))) {
            $decoded = json_decode($body, true);
            $err = 'Error calling '.$response->getRequestMethod().' '.$response->getUrl();
            if (isset($decoded['error'], $decoded['error']['message'], $decoded['error']['code'])
            ) {
                // if we're getting a json encoded error definition, use that instead of the raw response
                // body for improved readability
                $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
            } else {
                $err .= ": ({$code}) {$body}";
            }

            $errors = null;
            // Specific check for APIs which don't return error details, such as Blogger.
            if (isset($decoded['error'], $decoded['error']['errors'])) {
                $errors = $decoded['error']['errors'];
            }

            $map = null;
            if ($client) {
                $client->getLogger()->error(
                    $err,
                    ['code' => $code, 'errors' => $errors]
                );

                $map = $client->getClassConfig(
                    'SODOneDrive_Service_Exception',
                    'retry_map'
                );
            }

            throw new SODOneDrive_Service_Exception($err, $code, null, $errors, $map);
        }

        // 301 = Moved Permanently
        if ('301' == $code) {
            return $response->getResponseHeader('location');
        }

        // 302 = REDIRECT
        if ('302' == $code) {
            return $response->getResponseHeader('location');
        }
        // 202 = Accepted
        if ('202' == $code) {
            return $response->getResponseHeader('location');
        }

        // Only attempt to decode the response, if the response code wasn't (204) 'no content'
        if ('204' != $code) {
            if ($response->getExpectedRaw()) {
                return $body;
            }

            $decoded = json_decode($body, true);
            if (null === $decoded || '' === $decoded) {
                $error = "Invalid json in service response: {$body}";
                if ($client) {
                    $client->getLogger()->error($error);
                }

                throw new SODOneDrive_Service_Exception($error);
            }

            if ($response->getExpectedClass()) {
                $class = $response->getExpectedClass();
                $decoded = new $class($decoded);
            }
        }

        return $decoded;
    }

    /**
     * Parse/expand request parameters and create a fully qualified
     * request uri.
     *
     * @static
     *
     * @param string $servicePath
     * @param string $restPath
     * @param array  $params
     *
     * @return string $requestUrl
     */
    public static function createRequestUri($servicePath, $restPath, $params)
    {
        $requestUrl = $servicePath.$restPath;
        $uriTemplateVars = [];
        $queryVars = [];
        foreach ($params as $paramName => $paramSpec) {
            if ('boolean' == $paramSpec['type']) {
                $paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
            }
            if ('path' == $paramSpec['location']) {
                $uriTemplateVars[$paramName] = $paramSpec['value'];
            } elseif ('query' == $paramSpec['location']) {
                if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
                    foreach ($paramSpec['value'] as $value) {
                        $queryVars[] = $paramName.'='.rawurlencode($value);
                    }
                } else {
                    $queryVars[] = $paramName.'='.rawurlencode($paramSpec['value']);
                }
            }
        }

        if (count($uriTemplateVars)) {
            $uriTemplateParser = new SODOneDrive_Utils_URITemplate();
            $requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
        }

        if (count($queryVars)) {
            $requestUrl .= '?'.implode('&', $queryVars);
        }

        return $requestUrl;
    }
}
