<?php

namespace Drupal\yufu_concept\Plugin\rest\resource;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\node\NodeInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LogLevel;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Drupal\Component\Utility\Xss;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Creates post endpoint to create new concept.
 *
 * @RestResource(
 *   id = "concept_autocomplete_rest_resource",
 *   label = @Translation("Concept autocomplete endpoint"),
 *   uri_paths = {
 *     "canonical" = "/api/pojem/autocomplete",
 *     "create" = "/api/pojem/autocomplete",
 *   }
 * )
 */
class ConceptAutocomplete extends ResourceBase {

  /**
   * Entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array                  $configuration,
    string                 $plugin_id,
    array                  $plugin_definition,
    array                  $serializer_formats,
    LoggerInterface        $logger,
    EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.channel.yufu_concept'),
      $container->get('entity_type.manager')
    );
  }

  public function get(Request $request) {
    $results = [];
    $input = $request->query->get('q');// Get the typed string from the URL, if
                                       // it exists.
    $num = $request->query->get('num') ?? 10;
    $start = $request->query->get('start') ?? 0;
    if (!$input) {
      return new JsonResponse($results);
    }
    $input = Xss::filter($input);
    $node_storage = $this->entityTypeManager->getStorage('node');
    $query = $node_storage->getQuery()
      ->condition('type', 'concept')
      ->condition('title', $input, 'CONTAINS')
      ->groupBy('nid')
      ->sort('created', 'DESC')
      ->accessCheck(TRUE)
      ->range($start, $num);
    $ids = $query->execute();
    $nodes = $ids ? $node_storage->loadMultiple($ids) : [];
    foreach ($nodes as $id => $node) {
      $results[$id] = [
        'title' => $node->getTitle(),
        'id' => $node->id(),
        'revision_id' => $node->getRevisionId(),
        'revision_uid' => $node->getRevisionUserId(),
        'uuid' => $node->uuid(),
        'uid' => $node->uid->target_id,
      ];
    }
    return new JsonResponse($results);
  }

}
