<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\ffmpeg_media\Service\FormatterSettingsResolverInterface;

/**
 * Displays a setup banner on ffmpeg_media admin pages.
 */
final class SetupBannerHook {

  use StringTranslationTrait;

  /**
   * Constructs a SetupBannerHook object.
   *
   * @param \Drupal\ffmpeg_media\Service\FormatterSettingsResolverInterface $formatterSettingsResolver
   *   The formatter settings resolver service.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
   *   The current route match.
   */
  public function __construct(
    protected readonly FormatterSettingsResolverInterface $formatterSettingsResolver,
    protected readonly AccountProxyInterface $currentUser,
    protected readonly RouteMatchInterface $routeMatch,
  ) {}

  /**
   * Implements hook_page_top().
   *
   * Shows a warning banner when no formatter is configured.
   *
   * @param array<string, mixed> &$page_top
   *   The page top render array.
   */
  #[Hook('page_top')]
  public function pageTop(array &$page_top): void {
    if ($this->formatterSettingsResolver->hasAnyConfiguration()) {
      return;
    }

    if (!$this->currentUser->hasPermission('administer ffmpeg media')) {
      return;
    }

    $routeName = $this->routeMatch->getRouteName();
    if ($routeName === NULL) {
      return;
    }

    // Only show on ffmpeg_media routes (base module and all submodules).
    if (!str_starts_with($routeName, 'ffmpeg_media')) {
      return;
    }

    $page_top['ffmpeg_media_setup_banner'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['messages', 'messages--warning']],
      '#weight' => -100,
      'message' => [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->t('FFmpeg Media has no video formatter configured. Configure a video formatter under Manage Display for your media type to start converting videos.'),
      ],
      '#cache' => [
        'contexts' => ['user.permissions', 'route'],
      ],
    ];
  }

}
