<?php

namespace Drupal\edlp_corpus\Plugin\Filter;

use Drupal\Component\Utility\Html;
// use Drupal\Component\Utility\Unicode;
// use Drupal\Component\Utility\Xss;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\Core\Url;
// use Drupal\Core\Template\Attribute;

/**
 * Provides a filter to convert audio links.
 *
 * @Filter(
 *   id = "audio_links",
 *   title = @Translation("Audio Links"),
 *   description = @Translation("Convert enregistrement links to audio links"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
 * )
 */
class AudioLinksFilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $result = new FilterProcessResult($text);

    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    foreach ($xpath->query('//a[contains(@href, "node/")]') as $link) {
      $href = $link->getAttribute('href');
      preg_match('/^\/?node\/(\d+)$/', $href, $matches);
      // dpm($matches[1]);
      $node = entity_load('node', $matches[1]);

      if(!$node) continue;
      if($node->getType() != "enregistrement") continue;

      // dpm($node->getTitle());

      $options = ['absolute' => TRUE];
      $url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()], $options);
      $system_path = $url->getInternalPath();
      // get the audio file url
      $field_son_values = $node->get('field_son')->getValue();
      $son_fid = count($field_son_values) ? $field_son_values[0]['target_id'] : "";
      $son_file = \Drupal\file\Entity\File::load($son_fid);
      $son_url = null;
      if($son_file){
        $son_uri = $son_file->getFileUri();
        $son_url = file_create_url($son_uri);
      }
      // set the link classes
      $class = $link->getAttribute('class');
      $class .= $class == '' ? '':' ';
      $class .= 'audio-link ajax-link';

      // finnally add all the attributes 
      $link->SetAttribute('data-drupal-link-system-path', $system_path);
      $link->SetAttribute('audio_url', $son_url);
      $link->SetAttribute('nid', $node->id());
      $link->SetAttribute('class', $class);
    }

    $result->setProcessedText(Html::serialize($dom));
    return $result;
  }
}
