<?php

namespace Drupal\etherpad_api;

use Drupal\Core\Config\ImmutableConfig;
use GuzzleHttp\ClientInterface;

/**
 * Service description.
 */
class Client {

  /**
   * The HTTP client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * The config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  protected $apiKey = null;
  protected $baseUrl = null;

  // (Minimal) Etherpad version @TODO settings / get from instance?
  const API_VERSION = '1.2.1';

  /**
   * Constructs a Client object.
   *
   * @param \GuzzleHttp\ClientInterface $httpClient
   *   The HTTP client.
   * @param \Drupal\Core\Config\ImmutableConfig $config
   *   The config.
   */
  public function __construct(ClientInterface $httpClient, ImmutableConfig $config) {
    $this->httpClient = $httpClient;
    $this->config = $config;
    $this->baseUrl = $config->get('url') ? rtrim($config->get('url'), '/') : null;
    $this->apiKey = $config->get('key');
  }

  public function checkToken() {
    if ($this->baseUrl) {
      return $this->request('checkToken');
    }
    return false;
  }

  /**
   * Method description.
   */
  public function request($url, $opts = []) {
    $uri = "{$this->baseUrl}/" . self::API_VERSION . '/' . explode('?', $url)[0];
    if (!isset($opts['form_params'])) {
      $opts['form_params'] = [];
    }
    $opts['form_params']['apikey'] = $this->apiKey;
    $opts['verify'] = false;

    return $this->httpClient->post($uri, $opts);
  }
}
