<?php

namespace Drupal\edlp_corpus\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\workflow\Entity\WorkflowManager;
use Drupal\File\Entity\File;
use Symfony\Component\HttpFoundation\JsonResponse;


class CorpusController extends ControllerBase {


  /**
   * Display the markup.
   *
   * @return array
   */
  public function contentjson() {


    // @see https://www.droptica.com/blog/drupal-8-restjson-integration-simple-javascript-application/
    // @see https://www.sitepoint.com/drupal-8-version-entityfieldquery/
    // @see https://www.frobiovox.com/posts/2016/03/28/simplify-drupal-8-field-value-calls.html
    // @see https://chromatichq.com/blog/dependency-injection-drupal-8-plugins

    // Get a node storage object.
    // $file_storage = \Drupal::entityManager()->getStorage('node');

    $response = new JsonResponse();

    $config = \Drupal::config('system.site');

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'enregistrement');

    $nids = $query->execute();
    $nodes = entity_load_multiple('node', $nids);

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

    $nodes_data = [];
    foreach ($nodes as $node) {
      // this would be ideal but it's too heavy to load : the whole ajax json goes from 138kb to 1.23Md (even optimized)...
      // $node_builder = $view_builder->view($node, 'popup');

      // remove masqué
      $sid = WorkflowManager::getCurrentStateId($node, 'field_workflow');
      if($sid != 'corpus_documents_publie') continue;

      $entrees = [];
      foreach ($node->get('field_entrees')->getValue() as $key => $term) {
        $entrees[] = $term['target_id'];
      }
      // remove if no entries
      if(!count($entrees)) continue;

      $description_values = $node->get('field_description')->getValue();
      $description = count($description_values) ? $description_values[0]['value'] : "";
      // dpm($description);

      $field_son_values = $node->get('field_son')->getValue();
      $audio_fid = count($field_son_values) ? $field_son_values[0]['target_id'] : "";
      $audio_file = \Drupal\file\Entity\File::load($audio_fid);
      $audio_url = null;
      // if node don't have a sound file atteched, skip it
      if(!$audio_file) continue;

      $son_uri = $audio_file->getFileUri();
      $audio_url = file_create_url($son_uri);

      // has article ?
      $article_value = $node->body->getValue();
      $has_article = count($article_value);
      // if($has_article && $article_value[0]['value'] == "")
      //   dpm($article_value);

      // TODO: favoris marker

      $nodes_data[] = array(
        "nid" => $node->get('nid')->getString(),
        "title" => $node->get('title')->getString(),
        "description" => $description,
        "entrees" => $entrees,
        // "son_fid" => $audio_fid,
        "audio_url" => $audio_url,
        "has_article" => $has_article,
        "chutier_action" => 'add',
      );
    }

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

    $tids = $query->execute();
    // $nodes = entity_load_multiple('node', $nids);
    foreach ($tids as $tid) {
      $entrees[] = $tid;
    }

    $data = array(
      'date' => time(),
      'site_name' => $config->get('name'),
      'count' => count($nodes),
      'nodes' => $nodes_data,
      'entrees' => $entrees
    );

    $response->setData($data);

    return $response;
    // return array(
    //   '#markup'=>'Hello Corpus'
    // );
  }

}
