<?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;

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

  /**
   * 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 $plugin_definition */
    $plugin_definition = $this->blockManager->getDefinition($plugin_id);
    return $plugin_definition['admin_label'] ?? '';
  }

  /**
   * 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 $plugin_definition */
    $plugin_definition = $this->blockManager->getDefinition($plugin_id);
    return $plugin_definition['admin_label'] ?? '';
  }

}
