<?php

namespace Drupal\edlp_agenda\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Symfony\Component\HttpFoundation\JsonResponse;


class AgendaController extends ControllerBase {


  private function query() {
    // @see https://www.webomelette.com/query-entities-using-dates-drupal-8

    $now = new DrupalDateTime('now');
    $now->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'evenement')
      ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '>=')
      ->sort('field_date');

    $this->future_nids = $query->execute();
    $this->future_nodes = entity_load_multiple('node', $this->future_nids);

    $this->next_event = array_shift($this->future_nodes);

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'evenement')
      ->condition('field_date', $now->format(DATETIME_DATETIME_STORAGE_FORMAT), '<')
      ->sort('field_date', 'DESC');

    $this->past_nids = $query->execute();
    $this->past_nodes = entity_load_multiple('node', $this->past_nids);
  }

  private function toRenderable(){
    $this->query();
    // dpm($this->future_nodes);

    return array(
      "#theme"=>'edlp_agenda',
      '#next_event_node' => $this->next_event,
      "#coming_events_nodes" => $this->future_nodes,
      "#past_events_nodes" => $this->past_nodes,
    );

  }

  /**
   * Display agenda as a page.
   *
   * @return renderable array
   */
  public function agenda() {
    return $this->toRenderable();
  }

  /**
   * Get agenda data as json through ajax.
   *
   * @return json
   */
  public function agendajson() {

    $response = new JsonResponse();
    $renderable = $this->toRenderable();
    $rendered = render($renderable);

    $response->setData([
      'test'=>'hello',
      'rendered'=> $rendered
    ]);

    return $response;
  }

}
