<?php
// https://www.qed42.com/blog/autocomplete-drupal-8
// https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

namespace Drupal\materio_user\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormBuilder;
use Drupal\Core\Form\FormState;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
// use Drupal\Core\Cache\CacheableJsonResponse;
// use Drupal\Core\Cache\CacheableMetadata;
use Drupal\core\render\RenderContext;


/**
 * Defines a route controller for entity autocomplete form elements.
 */
class AjaxRegisterForm extends ControllerBase {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * Construct.
   */
  public function __construct(FormBuilder $formBuilder) {
    $this->formBuilder = $formBuilder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('form_builder')
    );
  }

  private function getFormDefinition(){
    // http://web-tricks.org/content/how-render-user-login-form-and-user-register-form-drupal-8
    $entity = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->create(array());
    // to use modal form display see materio_user_entity_type_build()
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'modal')
      ->setEntity($entity);
    $this->form_builded = $this->formBuilder()->getForm($formObject);
  }

  /**
   * Handler for getform request.
   */
  public function getForm(Request $request) {

    $this->getFormDefinition();

    // $rendered = render($this->form_builded);
    $rendered = \Drupal::service('renderer')->render($this->form_builded);
    // $form_builded = $this->form_builded;
    // $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($form_builded) {
    //     return render($form_builded);
    //   });
    $data = [
      'rendered' => $rendered,
      // '#cache' => [
      //   'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
      //   'tags' => [
      //     'materio_sapi-search_form-cache',
      //   ]
      // ]
    ];

    $response = new JsonResponse();
    $response->setData($data);
    // $response = new CacheableJsonResponse($data);
    // $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));

    return $response;
  }

}
