<?php

namespace Drupal\acquia_dam\Form;

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

/**
 * Acquia DAM image style configuration form.
 */
class AcquiaDamImageStyleConfigurationForm extends ConfigFormBase {

  /**
   * Image style helper service.
   *
   * @var \Drupal\acquia_dam\ImageStyleHelper
   */
  protected $imageStyleHelper;

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('acquia_dam.settings');

    $form['description'] = [
      '#markup' => '<p>' . $this->t('Configure which Drupal image styles are allowed to render Acquia DAM image assets. Only selected image styles will be available when displaying DAM assets.') . '</p>',
    ];

    $image_styles = [];
    foreach ($this->imageStyleHelper->getImageStylesBySupportStatus()['supported'] as $style) {
      $image_styles[$style->id()] = $style->label();
    }

    $form['image_style'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Allowed image styles'),
      '#description' => $this->t('Select which image styles should be allowed to render Acquia DAM image assets.'),
      '#description_display' => 'before',
      '#options' => $image_styles,
      '#default_value' => $config->get('allowed_image_styles') ?? [],
      '#size' => 6,
      '#multiple' => TRUE,
    ];

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $checkboxes = $form_state->getValue('image_style') ?? [];

    $this->config('acquia_dam.settings')
      ->set('allowed_image_styles', array_filter($checkboxes))
      ->save();

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

}
