<?php

declare(strict_types=1);

namespace Drupal\acquia_dam\Plugin\Linkit\Substitution;

use Drupal\Core\Entity\EntityInterface;
use Drupal\linkit\Plugin\Linkit\Substitution\Media;
use Drupal\media\MediaInterface;
use Drupal\acquia_dam\Plugin\media\Source\Asset;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A substitution plugin for the URL to a asset.
 *
 * Custom plugin for DAM assets because the source field is the DAM ID, not the
 * actual file reference field.
 *
 * @Substitution(
 *   id = "acquia_dam_asset",
 *   label = @Translation("Direct URL to Acquia DAM Assets"),
 * )
 */
class DamAsset extends Media {

  /**
   * Drupal entity type management service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    /** @var static $instance */
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->entityTypeManager = $container->get('entity_type.manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getUrl(EntityInterface $entity) {
    if ($entity instanceof MediaInterface) {
      $source = $entity->getSource();
      if ($source instanceof Asset) {
        $download_method = $source->getConfiguration()['download_assets'] ?: FALSE;
        if ($download_method) {
          $file_entity = $source->getMetadata($entity, 'file');
          if (!empty($file_entity)) {
            return $this->fileUrlGenerator->generate($file_entity->getFileUri());
          }
        }
        else {
          $asset_id = $source->getMetadata($entity, 'asset_id');
          $version_id = $source->getMetadata($entity, 'version_id');
          $uri = 'acquia-dam://' . $asset_id . '/' . $version_id;

          return $this->fileUrlGenerator->generate($uri);
        }
      }
    }

    return parent::getUrl($entity);
  }

}
