<?php

use \Drupal\Core\Url;
use Drupal\Component\Utility\Unicode;

use Drupal\edlp_studio\Entity\Chutier;

function template_preprocess_edlp_chutier_ui(&$vars){
  // dpm($vars);
  // $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

  $vars['documents'] = array (
    '#theme' => 'item_list',
    '#items' => [],
  );
  foreach($vars['document_nodes'] as $node){
    // get the url
    $url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()], ['absolute' => TRUE]);
    // 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);
    }
    // get the title
    $title = $node->getTitle();
    if(!$title) continue;
    $trunc_title = Unicode::truncate($title, 30, true, true);
    // classes
    $classes = array('audio-link', 'ajax-link');
    // get the entries
    $entrees = '';
    foreach ($node->get('field_entrees')->getValue() as $key => $term) {
      $entrees .= '<span class="entree" tid="'.$term['target_id'].'"></span>';
    }
    //
    // get the remove url (obviously as we are in chutier all contents actions are remove ;)
    $remove_url = Chutier::getActionsUrl($node->id(), $vars['uid']);

    // build the link
    $vars['documents']['#items'][] = array(
      '#type' => 'container',
      'entrees' => array(
        '#type' => 'container',
        '#attributes'=>['class'=>['entrees']],
        '#markup'=>$entrees,
      ),
      'link'=>array(
        '#title' => $trunc_title,
        '#type' => 'link',
        '#url' => $url,
        '#options'=>array(
          'attributes' => array(
            'data-drupal-link-system-path' => $url->getInternalPath(),
            'audio_url' => $son_url,
            'nid' => $node->id(),
            // 'tid' => $entrees[mt_rand(0, count($entrees) - 1)],
            // 'entries_size' => count($entrees),
            'class' => $classes,
            'title'=>$title,
          ),
        ),
      ),
      'remove_link' => array(
        '#title' => t("Chutier."),
        '#type' => 'link',
        '#url' => $remove_url,
        '#options'=>array(
          'attributes' => array(
            'data-drupal-link-system-path' => $remove_url->getInternalPath()
          ),
        ),
      ),
    );
  }

}
