<?php

namespace Drupal\etherpad_api\Form;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;

use Drupal\etherpad_api\Client;

/**
 * Configure Etherpad API settings for this site.
 */
class SettingsForm extends ConfigFormBase {
  protected $httpClient;
  protected $settings;

  public function __construct(ClientInterface $httpClient) {
    $this->httpClient = $httpClient;
    $this->settings = $this->config('etherpad_api.settings');
  }

  public static function create(ContainerInterface $container) {
    return new static($container->get('http_client'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'etherpad_api_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['etherpad_api.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Etherpad API URL'),
      '#required' => true,
      '#default_value' => $this->settings->get('url'),
    ];
    $form['key'] = [
      '#type' => 'password',
      '#title' => $this->t('Etherpad API key (found in instance root folder)'),
      '#default_value' => $this->settings->get('key'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Check API accessibility
    $apiKey = $form_state->getValue('key');

    if (!$apiKey) {
      $apiKey = $this->settings->get('key');
    }
    $baseUrl = $form_state->getValue('url');

    $url = rtrim($baseUrl, '/') . "/1.2/checkToken?apikey=$apiKey";
    try {
      $this->httpClient->request('get', $url);
    } catch (ClientException $e) {
      $form_state->setErrorByName('url', $this->t('Etherpad API not accessible (@code: @msg). The URL or the API key is wrong', [
        '@value' => $e->getCode(),
        '@msg' => $e->getMessage()
      ]));
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->settings->set('url', $form_state->getValue('url'));
    if ($form_state->getValue('key')) {
      $this->settings->set('key', $form_state->getValue('key'));
    }

    $this->settings->save();
    parent::submitForm($form, $form_state);
  }

}
