<?php
/*
	* @files
	* Theme Template Funtions
*/

use Drupal\Core\Template\Attribute;
use Drupal\Core\Link;
use Drupal\Core\Url;

// function popsu_preprocess_views_view_list(&$variables){
//   kint($variables);die();
// }

function popsu_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node){
    if($node->hasField('field_programme') && $node->get('field_programme')->getString() != ""){
      $variables['attributes']['class'][] = 'programme-' . $node->get('field_programme')->getString();
    }else{
      if ($node->id()){
        $variables['attributes']['class'][] = 'programme-' . $node->id();
      }
      
    }
  }
}

function popsu_preprocess_node(&$variables){
  
  $node = &$variables['node'];
  if($node->hasField('field_programme') && $node->get('field_programme')->getString() != ""){
    $variables['attributes']['class'][] = 'programme-' . $node->get('field_programme')->getString();
  }
}

function popsu_preprocess_field(&$variables){
  $element = &$variables['element'];
  if (isset($element['#field_name'])) {

    $variables['attributes']['class'][] = $element['#field_name'];
    if ($element['#field_name'] == 'field_texte') {
      $variables['attributes']['class'][] = 'crop';
    }
    if($element["#field_name"] == "field_programme"){
      foreach ($element["#items"]->getIterator() as $id => $item) {
        $nid = $item->getValue()['target_id'];
        $variables['items'][$id]['attributes']['class'] = new Attribute();
        $variables['items'][$id]['attributes']->addClass("programme-".$nid);
      }
    }
  }
  
}

function popsu_preprocess_views_view_unformatted(&$variables) {

  $view = &$variables['view'];  
  $rows = &$variables['rows'];
  if($view->id() == "programmes"){
    foreach ($rows as $id => $row) {
      $variables['rows'][$id]['attributes'] = new Attribute();
      $c = $variables['rows'][$id]['content']["#row"]->nid;
      $variables['rows'][$id]['attributes']->addClass("programme-".$c);
    }
  }else{
    foreach ($rows as $id => $row) {
      if(isset($row['content']['#row'])){
        $r = $row['content']['#row'];
        $entity = $r->_entity;
        if ($entity->hasField('field_programme') && $entity->get('field_programme')->getString() != "" ) {
          $c = $entity->get('field_programme')->getString();
          $variables['rows'][$id]['attributes'] = new Attribute();
          $variables['rows'][$id]['attributes']->addClass("programme-".$c);
          if ($entity->hasField('field_type_de_ressource') && $entity->get('field_type_de_ressource')->getString() == "74" ) {
            $type = $entity->get('field_type_de_ressource')->getString();
            $variables['rows'][$id]['attributes']['class'][] = "type-".$type;
          }
        }
      }else if(isset($row['content']['#node'])){
        $r = $row['content']['#node'];
        if ($r->hasField('field_programme') && $r->get('field_programme')->getString() != "" ) {
          $c = $r->get('field_programme')->getString();
          $variables['rows'][$id]['attributes'] = new Attribute();
          $variables['rows'][$id]['attributes']->addClass("programme-".$c);

        }
       
      }
      

   }
  }


};

/* implements template_preprocess_region() */

function popsu_preprocess_region(&$variables) {

  if (isset($variables['region'])) {
    $variables['attributes']['class'][] = $variables['region'].'_container'; 
  }

}


/**
 * Implements hook_preprocess_views_view_unformatted().
 */


function popsu_preprocess_views_view_grid(&$variables){
  // we pass all variables by reference
  // https://www.php.net/manual/en/language.references.php
  $items =& $variables['items'];

  // loop through grid items (row and cols) not through views\rows
  foreach ($items as $r => &$row) {
    foreach ($row['content'] as $c => &$col) {

      // get the entity
      $entity = $col['content']["#row"]->_entity;

      // build generique classe
      $classes = array(
        $entity->getEntityTypeId(),
        $entity->getEntityTypeId().'-'.$entity->bundle(),
        $entity->getEntityTypeId().'-'.$entity->bundle().'-'.$entity->id(),
      );
      // kint($entity);die();
      // if field_programme exists, add a class
      if ($entity->hasField('field_programme')) {
        $prog_id = $entity->get('field_programme')->getString();
        $classes[] = "programme-".$prog_id;
      }
      if ($entity->hasField('field_type_de_ressource')) {
        $type = $entity->get('field_type_de_ressource')->getString();
        $classes[] = "type-".$type;
      }

      // add the classes to the column
      // Drupal\Core\Template\Attribute 
      // https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/class/Attribute/8.2.x
      $col['attributes']->addClass($classes);
    }
  }
}

function popsu_preprocess_views_view_field(&$variables){
  // check if link to entity option is true
  $settings = isset($variables['field']->options['settings']) ? $variables['field']->options['settings'] : false; 
  if ($settings && isset($settings['link_to_entity']) && $settings['link_to_entity']) {
    // get the entity and build the classes
    $entity = $variables['row']->_entity;
    // $entity_type = $entity->getEntityType();
    if ($entity->getEntityType()->id() == "node" && $entity->id() == 5) {
      // temporarely desactivate popsumonde link
      // get the entity link and url
      $link = $entity->toLink(); 

      // // $url = $entity->toLink()->getUrl();
      // $url = URL::fromUserInput('#');
      // // update the url of the link
      // $link->setUrl($url);
      
      // overwrite the output
      $variables['output'] = [
        '#type' => 'html_tag',
        '#tag' => 'span',
        '#value' => $link->getText(),
        '#attributes' => [
          "class" => array(
            $entity->getEntityTypeId(),
            $entity->getEntityTypeId().'-'.$entity->bundle(),
            $entity->getEntityTypeId().'-'.$entity->bundle().'-'.$entity->id(),
          )
        ]
      ];
      
    }else{
      // build new classes
      $new_classes = array(
        $entity->getEntityTypeId(),
        $entity->getEntityTypeId().'-'.$entity->bundle(),
        $entity->getEntityTypeId().'-'.$entity->bundle().'-'.$entity->id(),
      );
      
      // get the entity link and url
      $link = $entity->toLink(); 
      $url = $entity->toLink()->getUrl();

      // set the active_class option to the url
      $url->setOption('set_active_class', true);

      // add new classes to the url (without overwriting existing once)
      $options = $url->getOptions();
      if(isset($options['attributes']) && $attributes = $options['attributes']){
        if(isset($attributes['class']) && $classes = $attributes['class']){
          $attributes['class'] +=  $new_classes;
        }else{
          $attributes['class'] = $new_classes;
        }
      }else{
        $attributes = array(
          "class" => $new_classes
        );
      }
      $url->setOption('attributes', $attributes);

      // update the url of the link
      $link->setUrl($url);

      // overwrite the output
      $variables['output'] = $link->toRenderable();

    }
  } 
}

function popsu_preprocess_block__entity_field(&$variables){
  $field = &$variables['content']['field'];
  $items = &$field['#items'];
  if ($field['#field_type'] === "entity_reference_revisions") {
    $entity = $items->first()->get('entity');
    $entityAdapter = $entity->getTarget();
    $referencedEntity = $entityAdapter->getValue();


    $field_definitions = $referencedEntity->getFieldDefinitions();
    $all_empty = TRUE;
    foreach ($field_definitions as $field_name => $definition) {
      if (!method_exists($definition, 'isBaseField')) {
        $field_instance = $referencedEntity->get($field_name);
        if (!$field_instance->isEmpty()) {
          $all_empty = FALSE;
        }
      }
    }
    if ($all_empty) {
      $variables['isEmpty'] = true;
    }



  }
}