<?php

namespace Drupal\pagedesigner_embed\Plugin\pagedesigner\Handler;

use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner_media\Plugin\MediaFieldHandlerBase;
use Drupal\video_embed_field\ProviderManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Process entities of type "embed".
 *
 * @PagedesignerHandler(
 *   id = "embed",
 *   name = @Translation("Embed handler"),
 *   types = {
 *      "embed"
 *   },
 * )
 */
class Embed extends MediaFieldHandlerBase {

  /**
   * The video embed provider manager.
   *
   * @var \Drupal\video_embed_field\ProviderManagerInterface
   */
  protected $providerManager = NULL;

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

  /**
   * Set the video embed provider manager.
   *
   * @param \Drupal\video_embed_field\ProviderManagerInterface $provider_manager
   *   The provider manager.
   */
  public function setProviderManager(ProviderManagerInterface $provider_manager) {
    $this->providerManager = $provider_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function collectAttachments(array &$attachments) {
    $attachments['library'][] = 'pagedesigner_embed/pagedesigner';
    static::addMediaTypeInfo($attachments, 'embed');
  }

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    $medium = static::getMediaTranslation($entity->field_media->entity);
    if ($medium != NULL && $medium->field_embed_source != NULL) {
      $provider = $this->providerManager->loadProviderFromInput($medium->field_embed_source->value);
      $renderArray = $provider->renderEmbedCode(0, 0, 0);
      $result = $renderArray['#url'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function generate($definition, array $data, ?Element &$entity = NULL) {
    parent::generate(['type' => 'embed', 'name' => 'embed'], $data, $entity);
  }

}
