<?php

namespace Drupal\edlp_ajax\Controller;

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


class EdlpAjaxController extends ControllerBase {

  private function query() {
    $this->entity = entity_load($this->entity_type, $this->id);
  }

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

    if($this->entity){
      return array(
        "#theme"=>'edlp_ajax',
        "#entity_type" => $this->entity_type,
        '#entity' => $this->entity,
        '#view_mode' => $this->viewmode,
      );
    }else{
      return array(
        '#markup'=>'404! '.$this->entity_type.' '.$this->id." not found!"
      );
    }
  }

  /**
   * Display entity as a page.
   *
   * @return renderable array
   */
  public function entity($entity_type, $id, $viewmode) {
    $this->entity_type = $entity_type;
    $this->id = $id;
    $this->viewmode = $viewmode;
    return $this->toRenderable();
  }

  /**
   * Get entity as json through ajax.
   *
   * @return json
   */
  public function entityjson($entity_type, $id, $viewmode) {
    $this->entity_type = $entity_type;
    $this->id = $id;
    $this->viewmode = $viewmode;
    $renderable = $this->toRenderable();
    $rendered = render($renderable);

    switch($this->entity_type){
      case 'node':
        $bundle = $this->entity->getType();
        break;
      case 'taxonomy_term':
        $bundle = $this->entity->bundle();
        break;
      default:
        $bundle = NULL;
    }

    $response = new JsonResponse();
    $response->setData([
      'test' => 'hello edlp ajax',
      'id' => $this->id,
      'view_mode' => $this->viewmode,
      'bundle' => $bundle,
      'entity_type' => $this->entity_type,
      'rendered'=> $rendered,
    ]);

    return $response;
  }

}
