<?php

namespace Drupal\nodehive_area_fragment\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Provides specific access control for the fragment entity type.
 *
 * @EntityReferenceSelection(
 *   id = "default:fragment_space",
 *   label = @Translation("Fragment space selection"),
 *   entity_types = {"nodehive_fragment"},
 *   group = "default",
 *   weight = 1
 * )
 */
class FragmentSpaceSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $configuration = $this->getConfiguration();

    // Only allow fragments that are part of the same space and have
    // the correct type set.
    if (isset($configuration['nodehive_area'])) {
      $area = $this->entityTypeManager
        ->getStorage('nodehive_area')
        ->load($configuration['nodehive_area']);
      $spaces = $area->space_id->referencedEntities();

      $allowed_spaces = [];
      foreach ($spaces as $space) {
        $allowed_spaces[] = $space->id();
      }

      if ($spaces) {
        $query->condition('space_id', $allowed_spaces, "IN");
      }

      $allowed_area_types = $area->allowed_fragment_types->referencedEntities();
      $types = [];

      foreach ($allowed_area_types as $entity) {
        $types[] = $entity->id();
      }

      if ($types) {
        $query->condition('type', $types, "IN");
      }
    }

    return $query;
  }

}
