<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\EventSubscriber;

use Drupal\Core\Template\AttributeHelper;
use Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent;
use Drupal\layout_builder\LayoutBuilderEvents;
use Drupal\sobki_background_image\Service\BackgroundImageStyleInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Add each component's background image to the render array.
 */
class BlockComponentRenderArraySubscriber implements EventSubscriberInterface {

  public function __construct(
    protected BackgroundImageStyleInterface $backgroundImageStyle,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = [];
    // Layout Builder also subscribes to this event to build the initial render
    // array. We use a higher weight so that we execute after it.
    $events[LayoutBuilderEvents::SECTION_COMPONENT_BUILD_RENDER_ARRAY] = [
      'onBuildRender',
      (int) 50,
    ];
    return $events;
  }

  /**
   * Add each component's background image to the render array.
   *
   * @param \Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent $event
   *   The section component render event.
   */
  public function onBuildRender(SectionComponentBuildRenderArrayEvent $event): void {
    $build = $event->getBuild();
    // This shouldn't happen - Layout Builder should have already created the
    // initial build data.
    if (empty($build)) {
      return;
    }
    $component = $event->getComponent();
    /** @var array $settings */
    $settings = $component->get('sobki_background_image') ?: [];

    $style = $this->backgroundImageStyle->getBackgroundImageStyle($settings);
    if (empty($style)) {
      return;
    }

    $build['#attributes'] = $build['#attributes'] ?? [];
    $build['#attributes'] = AttributeHelper::mergeCollections(
      $build['#attributes'],
      [
        'style' => $style,
      ]
    );
    $event->setBuild($build);
  }

}
