<?php

declare(strict_types=1);

namespace Drupal\sobki_admin\Service;

use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Helper service for the module.
 */
class Helper {

  use StringTranslationTrait;

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\CurrentRouteMatch
   */
  protected CurrentRouteMatch $currentRouteMatch;

  /**
   * The block manager.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected BlockManagerInterface $blockManager;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
   *   The current route match.
   * @param \Drupal\Core\Block\BlockManagerInterface $blockManager
   *   The block manager.
   */
  public function __construct(
    CurrentRouteMatch $currentRouteMatch,
    BlockManagerInterface $blockManager,
  ) {
    $this->currentRouteMatch = $currentRouteMatch;
    $this->blockManager = $blockManager;
  }

  /**
   * Get the route title.
   *
   * @return string|\Drupal\Component\Render\MarkupInterface
   *   The title.
   */
  public function getAddBlockRouteTitle(): MarkupInterface|string {
    /** @var string $plugin_id */
    $plugin_id = $this->currentRouteMatch->getParameter('plugin_id');
    /** @var array{admin_label: string|null} $plugin_definition */
    $plugin_definition = $this->blockManager->getDefinition($plugin_id);
    return $plugin_definition['admin_label'] ?? $this->t('Configure block');
  }

  /**
   * Get the route title.
   *
   * @return string|\Drupal\Component\Render\MarkupInterface
   *   The title.
   */
  public function getUpdateBlockRouteTitle(): MarkupInterface|string {
    /** @var \Drupal\layout_builder\SectionStorageInterface $section_storage */
    $section_storage = $this->currentRouteMatch->getParameter('section_storage');
    /** @var int $delta */
    $delta = $this->currentRouteMatch->getParameter('delta');
    /** @var string $uuid */
    $uuid = $this->currentRouteMatch->getParameter('uuid');
    $component = $section_storage->getSection($delta)->getComponent($uuid);
    $plugin_id = $component->getPluginId();
    /** @var array{admin_label: string|null} $plugin_definition */
    $plugin_definition = $this->blockManager->getDefinition($plugin_id);
    return $plugin_definition['admin_label'] ?? $this->t('Configure block');
  }

}
