<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\Form;

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

/**
 * Configuration form.
 */
class SettingsForm extends ConfigFormBase {

  public const CONFIG_NAME = 'sobki_background_image.media_mapping';

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected EntityFieldManagerInterface $entityFieldManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    $instance = parent::create($container);
    $instance->entityTypeManager = $container->get('entity_type.manager');
    $instance->entityFieldManager = $container->get('entity_field.manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return [
      static::CONFIG_NAME,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'sobki_background_image_settings_form';
  }

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

    $form['media_bundle_mapping'] = [
      '#type' => 'details',
      '#title' => $this->t('Media type mapping'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];

    $mediaTypes = $this->entityTypeManager->getStorage('media_type')
      ->loadMultiple();
    foreach ($mediaTypes as $mediaType) {
      $options = [];
      foreach ($this->entityFieldManager->getFieldDefinitions('media', (string) $mediaType->id()) as $fieldDefinition) {
        if ($fieldDefinition->getType() == 'image') {
          $options[$fieldDefinition->getName()] = $fieldDefinition->getLabel();
        }
      }

      $form['media_bundle_mapping'][$mediaType->id()] = [
        '#type' => 'select',
        '#title' => $mediaType->label(),
        '#options' => $options,
        '#default_value' => $config->get('media_bundle_mapping.' . $mediaType->id()) ?? '',
        '#empty_value' => '',
        '#empty_option' => $this->t('Not used'),
      ];
    }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    parent::submitForm($form, $form_state);
    $mapping = $form_state->getValue('media_bundle_mapping');
    if (!\is_array($mapping)) {
      $mapping = [];
    }
    $this->config(static::CONFIG_NAME)
      ->set('media_bundle_mapping', \array_filter($mapping))
      ->save();
  }

}
