<?php

declare(strict_types=1);

namespace Drupal\acquia_dam\Entity;

use Drupal\acquia_dam\Plugin\Field\FieldType\AssetFieldType;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Provides storage and field definitions for the DAM media source plugin.
 */
final class MediaItemField {

  /**
   * Get the storage definition.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   * @param array $plugin_definition
   *   An array containing the media source plugin definition.
   */
  public static function getStorageDefinition(string $entity_type_id, array $plugin_definition): BundleFieldDefinition {
    return self::bundleFieldDefinition($plugin_definition)
      ->setTargetEntityTypeId($entity_type_id);
  }

  /**
   * Get the field definition.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   * @param string $bundle
   *   The entity bundle.
   * @param array $plugin_definition
   *   An array containing the media source plugin definition.
   */
  public static function getFieldDefinition(string $entity_type_id, string $bundle, array $plugin_definition): BundleFieldDefinition {
    return self::bundleFieldDefinition($plugin_definition)
      ->setTargetEntityTypeId($entity_type_id)
      ->setTargetBundle($bundle);
  }

  /**
   * Get the bundle field definition.
   *
   * @param array $plugin_definition
   *   An array containing the media source plugin definition.
   */
  private static function bundleFieldDefinition(array $plugin_definition): BundleFieldDefinition {
    $media_source_id = self::getMediaSourceId($plugin_definition);
    return BundleFieldDefinition::create(AssetFieldType::BASE_FIELD_NAME . ":" . $media_source_id)
      ->setProvider('acquia_dam')
      ->setLabel(new TranslatableMarkup('The Acquia DAM field for %label', ['%label' => $media_source_id]))
      ->setName(self::getFieldName($media_source_id))
      ->setComputed(TRUE)
      ->setReadOnly(TRUE);
  }

  /**
   * Get the field name for a given media source ID.
   *
   * @param string $media_source_id
   *   The media source ID.
   */
  public static function getFieldName(string $media_source_id): string {
    return AssetFieldType::BASE_FIELD_NAME . "_". $media_source_id . "_item";
  }


  /**
   * Extracts the media source ID from the plugin definition.
   *
   * @param array $plugin_definition
   *   An array containing the media source plugin definition.
   */
  public static function getMediaSourceId(array $plugin_definition): string {
    $media_source_id = $plugin_definition['id'] ?? NULL;
    assert(is_string($media_source_id) && !empty($media_source_id), 'Media source ID must present.');
    return $media_source_id;
  }

}
