<?php

namespace Drupal\node_view_mode\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure Node View Mode settings.
 */
class NodeViewModeSettingsForm extends ConfigFormBase {

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->entityDisplayRepository = $container->get('entity_display.repository');
    return $instance;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('node_view_mode.settings');
    $enabled_modes = $config->get('enabled_view_modes') ?: ['full'];

    $view_modes = $this->entityDisplayRepository->getViewModes('node');
    $options = ['full' => $this->t('Full')];
    foreach ($view_modes as $mode => $info) {
      $options[$mode] = $info['label'];
    }

    $form['enabled_view_modes'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Enabled view modes'),
      '#description' => $this->t('Select which view modes this module should process.'),
      '#options' => $options,
      '#default_value' => $enabled_modes,
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = array_filter($form_state->getValue('enabled_view_modes'));

    $this->config('node_view_mode.settings')
      ->set('enabled_view_modes', array_values($values))
      ->save();

    parent::submitForm($form, $form_state);
  }

}
