<?php

namespace Drupal\edlp_productions\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Symfony\Component\HttpFoundation\JsonResponse;


class ProductionsController extends ControllerBase {

  private function query() {
    // TODO: get the production menu
    // @see https://api.drupal.org/api/drupal/core%21modules%21menu_ui%21menu_ui.module/8.6.x
    // @see https://drupal.stackexchange.com/questions/200893/get-menu-link-page-settings-from-view-configuration
    $menu_name = 'productions';

    $query = \Drupal::entityQuery('menu_link_content')
            ->condition('menu_name', $menu_name)
            ->condition('enabled', 1)
            ->sort('weight', 'ASC');

    $result = $query->execute();
    // dpm($result);

    $nids = [];
    foreach ($result as $id) {
      $menu_link = MenuLinkContent::load($id);
      // dpm($menu_link->getParentId());
      if($menu_link->getParentId() !== "") continue;

      // dpm($menu_link->getTitle());
      $path = $menu_link->getUrlObject()->getInternalPath();
      preg_match('/^(node)\/(\d+)$/', $path, $m);
      // dpm($m);
      if($m[1] !== "node") continue;

      $nids[] = ($m[2]);
    }

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

  }


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

    // TODO: add localtasks to each nodes : https://api.drupal.org/api/drupal/core%21includes%21menu.inc/function/menu_primary_local_tasks/8.2.x

    return array(
      "#theme"=>'edlp_productions',
      "#nodes_entities"=>$this->nodes,
    );

  }

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


  private function getProductionBlock(){
    $block = \Drupal\block\Entity\Block::load('productions');

    return $block;
  }

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

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

    // add menu production block
    $block = $this->getProductionBlock();
    $block_render = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);


    $response->setData([
      'test'=>'hello',
      'rendered'=> $rendered,
      'block' => array(
        'rendered'=> \Drupal::service('renderer')->renderRoot($block_render),
        'region'=> str_replace('_', '-', $block->getRegion()),
        'id'=> preg_replace('/^[^:]+:(.+)$/', 'block-$1', $block->getPluginId())
      )
    ]);

    return $response;
  }

}
