<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media_player\Service;

use Drupal\Core\Config\ConfigFactoryInterface;

/**
 * Resolves player configuration by merging global and formatter settings.
 *
 * @internal
 */
final class PlayerConfigResolver implements PlayerConfigResolverInterface {

  /**
   * Constructs a PlayerConfigResolver object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory service.
   */
  public function __construct(
    protected readonly ConfigFactoryInterface $configFactory,
  ) {}

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function resolve(
    array $formatterSettings,
    array $sources,
    int $mediaId,
    ?string $poster = NULL,
    array $subtitles = [],
    string $title = '',
  ): array {
    $defaults = $this->getDefaults();

    // Merge formatter settings with global defaults.
    return [
      'mediaId' => $mediaId,
      'sources' => $sources,
      'poster' => $poster,
      'subtitles' => $subtitles,
      'autoplay' => (bool) ($formatterSettings['autoplay'] ?? $defaults['autoplay']),
      'muted' => (bool) ($formatterSettings['muted'] ?? $defaults['muted']),
      'loop' => (bool) ($formatterSettings['loop'] ?? $defaults['loop']),
      'controls' => (bool) ($formatterSettings['controls'] ?? $defaults['controls']),
      'preload' => (string) ($formatterSettings['preload'] ?? $defaults['preload']),
      'aspectRatio' => $this->validateAspectRatio((string) ($formatterSettings['aspect_ratio'] ?? $defaults['aspectRatio'])),
      'lazyLoad' => (bool) ($formatterSettings['lazy_load'] ?? $defaults['lazyLoad']),
      'theme' => (string) ($formatterSettings['player_theme'] ?? $defaults['theme']),
      'keyboardNavigation' => (bool) $defaults['keyboardNavigation'],
      'posterLoadingPriority' => (string) $defaults['posterLoadingPriority'],
      'crossOrigin' => (string) $defaults['crossOrigin'],
      'storage' => (string) $defaults['storage'],
      'title' => $title,
      'streamType' => (string) ($formatterSettings['stream_type'] ?? $defaults['streamType']),
      'enablePip' => (bool) $defaults['enablePip'],
      'enablePlaybackSpeed' => (bool) $defaults['enablePlaybackSpeed'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function getDefaults(): array {
    $config = $this->configFactory->get('ffmpeg_media_player.settings');

    return [
      'autoplay' => FALSE,
      'muted' => FALSE,
      'loop' => FALSE,
      'controls' => TRUE,
      'preload' => $config->get('preload_strategy') ?? 'metadata',
      'aspectRatio' => $config->get('default_aspect_ratio') ?? '16:9',
      'lazyLoad' => (bool) ($config->get('lazy_load_enabled') ?? TRUE),
      'theme' => $config->get('default_theme') ?? 'default',
      'keyboardNavigation' => (bool) ($config->get('enable_keyboard_navigation') ?? TRUE),
      'posterLoadingPriority' => $config->get('poster_loading_priority') ?? 'high',
      'crossOrigin' => $config->get('crossorigin') ?? 'none',
      'storage' => $config->get('storage_key') ?? 'ffmpeg-media',
      'streamType' => 'on-demand',
      'enablePip' => (bool) ($config->get('enable_pip') ?? TRUE),
      'enablePlaybackSpeed' => (bool) ($config->get('enable_playback_speed') ?? TRUE),
    ];
  }

  /**
   * Validates aspect ratio against allowed values.
   *
   * @param string $aspectRatio
   *   The aspect ratio to validate.
   *
   * @return string
   *   The validated aspect ratio, or '16:9' as fallback.
   */
  private function validateAspectRatio(string $aspectRatio): string {
    $allowedRatios = ['auto', '16:9', '4:3', '21:9', '1:1', '9:16'];
    if (!in_array($aspectRatio, $allowedRatios, TRUE)) {
      return '16:9';
    }
    return $aspectRatio;
  }

}
