<?php

declare(strict_types=1);

namespace Drupal\acquia_dam\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Derives field types for each Acquia DAM media source plugin.
 */
class AssetSourceFieldTypeDeriver extends DeriverBase implements ContainerDeriverInterface {

  /**
   * Constructs a new AssetSourceFieldTypeDeriver instance.
   *
   * @param \Drupal\Component\Plugin\PluginManagerInterface $mediaSourceManager
   *   The media source plugin manager.
   */
  public function __construct(
    private readonly PluginManagerInterface $mediaSourceManager
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id): static {
    return new static(
      $container->get('plugin.manager.acquia_dam.asset_media_source')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition): array {
    $media_sources = $this->mediaSourceManager->getDefinitions();
    foreach ($media_sources as $media_source) {
      $id = $media_source['id'];
      $this->derivatives[$id] = $base_plugin_definition;
      $this->derivatives[$id]['id'] = $media_source['id'];
      $field_list_item_class = $media_source['field_list_item_class'] ?? NULL;
      $field_type_class = $media_source['field_type_class'] ?? NULL;
      if ($field_list_item_class) {
        assert(class_exists($field_list_item_class) && is_subclass_of($field_list_item_class, FieldItemListInterface::class));
        $this->derivatives[$id]['list_class'] = $field_list_item_class;
      }
      if ($field_type_class) {
        assert(class_exists($field_type_class) && is_subclass_of($field_type_class, FieldItemInterface::class));
        $this->derivatives[$id]['class'] = $field_type_class;
      }
    }
    return $this->derivatives;
  }


}
