<?php

namespace PeytzMail\Client;

use PeytzMail\Config;
use PeytzMail\Client;
use PeytzMail\Exception\RuntimeException;
use Buzz\Browser;
use Buzz\Client\ClientInterface;
use Buzz\Client\Curl;
use Buzz\Listener\BasicAuthListener;
use Buzz\Message\RequestInterface;

/**
 * @package PeytzMail
 */
class BuzzClient implements Client
{
    protected $headers;
    protected $client;
    protected $endPoint;

    /**
     * {@inheritdoc}
     */
    public function __construct(Config $config, ClientInterface $client = null)
    {
        $this->headers = array(
            'Accept: application/json',
            'Content-Type: application/json',
        );

        $this->browser = new Browser($client ?: new Curl);
        $this->browser->addListener(new BasicAuthListener($config->getApiKey(), ''));

        $this->endPoint = $config->getEndPoint();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'Buzz';
    }

    /**
     * {@inheritdoc}
     */
    public function getContent($path, $data = null, $method = RequestInterface::METHOD_GET)
    {
        $path = sprintf('%s%s', $this->endPoint, $path);
        $data = json_encode($data);

        $apiCall = $this->browser->call($path, $method, $this->headers, $data);

        if (!$apiCall->isSuccessful()) {
            $message = json_decode($apiCall->getContent());

            if (null === $message) {
                $message = 'Not found - please check your endpoint.';
            } else {
                $message = property_exists($message, 'message') ? $message->message : 'No message associated to this error.';
            }

            throw new RuntimeException(
                sprintf('[Peytz Mail] %d - %s', $apiCall->getStatusCode(), $message), $apiCall->getStatusCode()
            );
        };

        return $apiCall->getContent();
    }
}
