<?php

namespace Drupal\autoslave\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Autoslave Settings Form.
 */
class AutoslaveSettingsForm extends ConfigFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!autoslave_is_driver_loaded()) {
      \Drupal::messenger()->addMessage('AutoSlave driver is not loaded', 'warning');
    }

    $config = $this->config('autoslave.settings');

    $form['autoslave_dashboard_deltas'] = [
      '#title' => $this->t('Number of bars to put into the dashboard for each server.'),
      '#description' => $this->t('The bar graph on /admin/config/system/autoslave assumes by default that you want 30 bars.  If you lower this value to say 20, you will see 20 vertical bars on the graph.  With less deltas the graph could be easier to read however as a tradeoff you will see less data!'),
      '#type' => 'number',
      '#default_value' => !empty($config->get('autoslave_dashboard_deltas')) ? $config->get('autoslave_dashboard_deltas') : 30,
    ];
    $form['autoslave_debug_mode'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable autoslave debug mode (for more detailed logging in watchdog).'),
      '#description' => $this->t('If checked, autoslave debug mode will be enabled.'),
      '#default_value' => $config->get('autoslave_debug_mode'),
    ];
    $form['autoslave_dashboard_url_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('URL hash parameter'),
      '#description' => $this->t('Set the URL parameter for hashed key,
      for example: http://example.com/admin/config/system/autoslave/dashboard?<strong>hash</strong>=abc...,
      example.com/admin/config/system/autoslave/dashboard?<strong>key</strong>=abc...'),
      '#maxlength' => 20,
      '#size' => 10,
      '#default_value' => !empty($config->get('autoslave_dashboard_url_key')) ? $config->get('autoslave_dashboard_url_key') : 'Hash',
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('autoslave.settings')
      ->set('autoslave_dashboard_deltas', $form_state->getValue('autoslave_dashboard_deltas'))
      ->set('autoslave_debug_mode', $form_state->getValue('autoslave_debug_mode'))
      ->set('autoslave_dashboard_url_key', $form_state->getValue('autoslave_dashboard_url_key'))
      ->save();
    parent::submitForm($form, $form_state);
  }

}
