<?php

declare(strict_types=1);

namespace Drupal\acquia_dam\Entity;

use Drupal\Core\StringTranslation\TranslatableMarkup;

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

  /**
   * The field name.
   */
  public const MANAGED_IMAGE_FIELD_NAME = 'acquia_dam_managed_image';

  /**
   * Get the field storage definition.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   *
   * @return \Drupal\acquia_dam\Entity\BundleFieldDefinition
   *   The storage definition.
   */
  public static function getStorageDefinition(string $entity_type_id): BundleFieldDefinition {
    return self::bundleFieldDefinition()->setTargetEntityTypeId($entity_type_id);
  }

  /**
   * Get the field definition.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   * @param string $bundle_id
   *   The entity bundle ID.
   *
   * @return \Drupal\acquia_dam\Entity\BundleFieldDefinition
   *   The field definition.
   */
  public static function getFieldDefinition(string $entity_type_id, string $bundle_id): BundleFieldDefinition {
    // Get uri_scheme from media type source.
    $media_type = \Drupal::entityTypeManager()->getStorage('media_type')->load($bundle_id);
    $uri_scheme = $media_type->getSource()->getUriScheme();
    $file_extensions = $media_type->getSource()->getFileExtensions();

    return self::bundleFieldDefinition($uri_scheme, $file_extensions)
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setTargetEntityTypeId($entity_type_id)
      ->setTargetBundle($bundle_id);
  }

  /**
   * Get the bundle field definition.
   *
   * @param string $uri_scheme
   *   The URI scheme for file storage (public or private).
   * @param string $file_extensions
   *   The allowed file extensions, separated by a comma.
   *
   * @return \Drupal\acquia_dam\Entity\BundleFieldDefinition
   *   The bundle field definition.
   *
   * @see \Drupal\image\Plugin\Field\FieldType\ImageItem::defaultFieldSettings()
   */
  private static function bundleFieldDefinition(string $uri_scheme = '', string $file_extensions = ''): BundleFieldDefinition {
    $bundle_field_definition = BundleFieldDefinition::create('image')
      ->setSetting('uri_scheme', $uri_scheme)
      ->setProvider('acquia_dam')
      ->setName(self::MANAGED_IMAGE_FIELD_NAME)
      ->setDescription(t('For keeping track of locally stored images of DAM assets.'))
      ->setLabel(new TranslatableMarkup('On-site stored asset image'))
      ->setReadOnly(FALSE);

    if (!empty($file_extensions)) {
      $bundle_field_definition->setSetting('file_extensions', $file_extensions);
    }

    return $bundle_field_definition;
  }

}
