<?php
namespace boru\ai\Tests\Fakes;

use boru\ai\Http\HttpClientInterface;
use boru\ai\Http\HttpRequest;
use boru\ai\Http\HttpResponse;

class FakeHttpClient implements HttpClientInterface
{
    /** @var HttpRequest[] */
    public $requests = array();

    /** @var HttpResponse[] */
    public $responses = array();

    /** @var array[] */
    public $streamChunks = array();

    public function queueResponse(HttpResponse $response)
    {
        $this->responses[] = $response;
        return $this;
    }

    public function queueStream(array $chunks, HttpResponse $response = null)
    {
        $this->streamChunks[] = $chunks;
        if ($response !== null) {
            $this->responses[] = $response;
        }
        return $this;
    }

    public function send(HttpRequest $request)
    {
        $this->requests[] = $request;

        if ($request->streamCallback()) {
            $chunks = !empty($this->streamChunks) ? array_shift($this->streamChunks) : array();
            if (!empty($this->responses)) {
                $response = array_shift($this->responses);
            } else {
                $response = new HttpResponse();
                $response->statusCode(200);
            }

            foreach ($chunks as $chunk) {
                call_user_func($request->streamCallback(), $chunk, $response);
            }

            return $response;
        }

        if (empty($this->responses)) {
            throw new \RuntimeException('No queued fake HTTP response');
        }

        return array_shift($this->responses);
    }
}
