<?php

/**
 * @file
 */
namespace Drupal\edlp_corpus\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\workflow\Entity\WorkflowManager;

/**
 * Creates a 'Entrees' Block
 * @Block(
 * id = "block_edlp_entrees",
 * admin_label = @Translation("Edlp entrees block"),
 * )
 */
class BlockEntrees extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $query = \Drupal::entityQuery('taxonomy_term')
      ->condition('vid', 'entrees');

    $tids = $query->execute();
    $terms = entity_load_multiple('taxonomy_term', $tids);
    // dsm($terms);
    foreach ($terms as $term) {
      // dpm($term->toArray());
      $tid = $term->id();
      $name = $term->getName();

      // remove masqué
      $sid = WorkflowManager::getCurrentStateId($term, 'field_workflow');
      if($sid == 'generique_masque') continue;

      $entree = array(
        'tid'=>$tid
      );

      // term name
      $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term'=>$tid]);
      $url->setOptions(array(
        'attributes' => array(
          'class' => ['term-'.$tid, 'term-link'],
          'tid'=>$tid,
          'data-drupal-link-system-path' => $url->getInternalPath()
        )
      ));
      $entree['term_link'] = Link::fromTextAndUrl($name, $url);

      // index link
      $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term'=>$tid]);
      $url->setOptions(array(
        'attributes' => array(
          'class' => ['index-link', 'ajax-link'],
          'viewmode'=>'index',
          'tid'=>$tid,
          'data-drupal-link-system-path' => $url->getInternalPath()
        )
      ));
      $entree['index_link'] = Link::fromTextAndUrl('index', $url);

      // notice-link
      $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term'=>$tid]);
      $url->setOptions(array(
        'attributes' => array(
          'class' => ['notice-link', 'ajax-link'],
          'viewmode'=>'notice',
          'tid'=>$tid,
          'data-drupal-link-system-path' => $url->getInternalPath()
        )
      ));
      $entree['notice_link'] = Link::fromTextAndUrl('notice', $url);

      $entree['description'] = $term->get('description')->value;

      $entrees[] = $entree;
    }

    return array (
      '#theme' => 'blockentrees',
      '#entrees_items' => $entrees,
      '#attached'=>array(
        'library' => array('edlp_corpus/corpus'),
        'drupalSettings' => array(
          'basepath' => base_path()
        )
      )
    );
  }

}
