<?php

namespace Magic\Http;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;

class Http
{
    /** @var GuzzleHttp\ClientInterface */
    protected $httpClient;

    /**
     * Http Constructor
     *
     * @param GuzzleHttp\ClientInterface|null $httpClient
     */
    protected function __construct($httpClient = null)
    {
        $this->httpClient = $httpClient ?? $this->httpClient();
    }

    /**
     * Create new instance of Magic\Http\Http
     * @param  ClientInterface|null $httpClient
     * @return Magic\Http\Http
     */
    public static function new(ClientInterface $httpClient = null)
    {
        return new self($httpClient);
    }

    /**
     * Get the http client
     *
     * @return GuzzleHttp\ClientInterface
     */
    public function httpClient()
    {
        if (!$this->httpClient) {
            $this->httpClient = new Client([
                'User-Agent' => 'magic-cli'
            ]);
        }

        return $this->httpClient;
    }

    /**
     * Magic method for handling http client requests
     *
     * @param  String $method
     * @param  array $parameters
     * @return Psr\Http\Message\ResponseInterface
     */
    public function __call($method, $parameters)
    {
        return call_user_func_array([$this->httpClient(), $method], $parameters);
    }
}
