<?php

namespace Dipper\Foundation\Http\GuzzleMiddlewares;

use Log;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Promise\PromiseInterface;

/**
 * Class LogMiddleware.
 */
class LogMiddleware extends MiddlewareAbstract
{
    public function handle()
    {
        return Middleware::tap(function (RequestInterface $request, $options) {
            if (config('dipper.guzzle.log_middleware_debug')) {
                $this->logRequest($request, $options);
            }
        }, function (RequestInterface $request, $options, $response) {
            if (config('dipper.guzzle.log_middleware_debug')) {
                $this->logResponse($request, $options, $response);
            }
        });
    }

    protected function logRequest($request, $options)
    {
        Log::debug('Guzzel', [
                'Type' => 'Guzzel Request',
                'Url' => $request->getUri()->__toString(),
                'Method' => $request->getMethod(),
                'Headers' => $request->getHeaders(),
                // 'Options' => $options,
        ]);
    }

    protected function logResponse($request, $options, $response)
    {
        if ($response instanceof ResponseInterface) {
            $response = $response;
        } elseif ($response instanceof PromiseInterface) {
            $response = $response->wait();
        } else {
            $response = null;
        }

        if ($response) {
            Log::debug('Guzzle', [
                'Type' => 'Guzzel Response',
                'Status' => $response->getStatusCode(),
                'Body' => strval($response->getBody()),
                'Reason' => $response->getReasonPhrase(),
                'Headers' => $response->getHeaders(),
            ]);
        }
    }

    public function getMiddlewareName()
    {
        return 'log_middleware';
    }
}
