<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\HookHandler;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\sobki_background_image\Form\SettingsForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Block layout alter.
 */
class FormBlockFormAlter implements ContainerInjectionInterface {

  use StringTranslationTrait;

  public function __construct(
    protected ConfigFactoryInterface $configFactory,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('config.factory')
    );
  }

  /**
   * Add background image on block config form.
   *
   * @param array $form
   *   The form structure.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The form state.
   */
  public function blockFormAlter(array &$form, FormStateInterface $formState): void {
    /** @var \Drupal\block\BlockForm $form_object */
    $form_object = $formState->getFormObject();
    if (!($form_object instanceof EntityFormInterface)) {
      return;
    }

    $config = $this->configFactory->get(SettingsForm::CONFIG_NAME);
    $mapping = $config->get('media_bundle_mapping');
    if (!\is_array($mapping)) {
      return;
    }

    $allowedBundles = \array_keys($mapping);
    if (empty($allowedBundles)) {
      return;
    }

    /** @var \Drupal\block\BlockInterface $block */
    $block = $form_object->getEntity();
    $settings = $block->getThirdPartySettings('sobki_background_image');

    $form['sobki_background_image'] = [
      '#type' => 'sobki_background_image',
      '#title' => $this->t('Background image'),
      '#media_bundles' => $allowedBundles,
      '#default_value' => $settings,
    ];
  }

}
