<?php

namespace Drupal\nodehive_core;

use Drupal\Core\Entity\EntityAutocompleteMatcher;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;

/**
 * Matcher class to get autocompletion results for entity reference.
 */
class EntityReferenceAutocompleteMatcher extends EntityAutocompleteMatcher {

  /**
   * The entity reference selection handler plugin manager.
   *
   * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
   */
  protected $selectionManager;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

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

  /**
   * Constructs an EntityAutocompleteMatcher object.
   *
   * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager
   *   The entity reference selection handler plugin manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(
    SelectionPluginManagerInterface $selection_manager,
    AccountProxyInterface $current_user,
    EntityTypeManagerInterface $entity_type_manager,
  ) {
    $this->selectionManager = $selection_manager;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {
    $matches = parent::getMatches($target_type, $selection_handler, $selection_settings, $string);

    if ($target_type != "nodehive_space") {
      return $matches;
    }

    if (in_array("administrator", $this->currentUser->getRoles()) || $this->currentUser->id() == 1) {
      return $matches;
    }

    foreach ($matches as $key => $match) {
      preg_match('#\((.*?)\)#', $match['value'], $item);
      $id = $item[1];

      $space = $this->entityTypeManager->getStorage('nodehive_space')->load($id);
      if (!$space) {
        unset($matches[$key]);
      }

      $has_user_access = FALSE;
      $editors = $space->editors->referencedEntities();
      foreach ($editors as $editor) {
        if ($editor->id() == $this->currentUser->id()) {
          $has_user_access = TRUE;
        }
      }

      if (!$has_user_access) {
        unset($matches[$key]);
      }

    }

    return $matches;
  }

}
