<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Template\AttributeHelper;
use Drupal\block\BlockInterface;
use Drupal\sobki_background_image\Service\BackgroundImageStyleInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Add classes to block.
 */
class PreprocessBlock implements ContainerInjectionInterface {

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('sobki_background_image.background_image_style')
    );
  }

  /**
   * Inject background image.
   *
   * @param array $variables
   *   The preprocessed variables.
   */
  public function preprocess(array &$variables): void {
    // Blocks coming from page manager widget does not have id. If there is no
    // Block ID, skip that.
    if (empty($variables['elements']['#id'])) {
      return;
    }

    // Load the block by ID.
    $block = $this->entityTypeManager->getStorage('block')
      ->load($variables['elements']['#id']);

    // If there is no block with this ID, skip.
    if (!($block instanceof BlockInterface)) {
      return;
    }

    $this->addBackgroundImageOnBlock($block, $variables);
  }

  /**
   * Add background image on block.
   *
   * @param \Drupal\block\BlockInterface $block
   *   The block being preprocessed.
   * @param array $variables
   *   The variables being preprocessed.
   */
  protected function addBackgroundImageOnBlock(BlockInterface $block, array &$variables): void {
    $settings = $block->getThirdPartySettings('sobki_background_image');
    $style = $this->backgroundImageStyle->getBackgroundImageStyle($settings);
    if (empty($style)) {
      return;
    }

    $variables['attributes'] = AttributeHelper::mergeCollections(
      $variables['attributes'],
      [
        'style' => $style,
      ]
    );
  }

}
