<?php


namespace Drupal\mapui\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\Annotation\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use \Drupal\Core\StringTranslation\TranslationManager;
//use Drupal\Core\Entity\Plugin\EntityReferenceSelection;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;


/**
 * Provides specific access control for the boutique node type.
 *
 * @EntityReferenceSelection(
 *   id = "default:boutique",
 *   label = @Translation("Boutique Selection minus Empty Buildings"),
 *   entity_types = {"node"},
 *   group = "default",
 *   weight = 1
 * )
 */
class BoutiqueSelection extends NodeSelection {


  public function entityQueryAlter(SelectInterface $query) {
    parent::entityQueryAlter($query);

    //Get the tid for the term which was used to tag nodes which should be EXCLUDED from the results

    $emptyTid = array_values(\Drupal::entityQuery('taxonomy_term')
      ->condition('name', 'Empty')
      ->execute())[0];

    if ($emptyTid != null && $emptyTid > -1) {

    //Get nids for nodes which were tagged with this term

      $excludeQuery = db_query('
        SELECT entity_id 
        FROM node__field_store_type 
        WHERE field_store_type_target_id = :tid',

        array(
          ':tid' => $emptyTid
        )
      )->fetchAllKeyed(0, 0);

      //Reset array keys
      $result = array_values($excludeQuery);

      $typecastedResult = array();
      //Typecast all the values to int, just to be safe
      foreach ($result as $k => $v) {
        $typecastedResult[] = (int)$v;
      }
      //Add a condition to the query such as to exclude the nodes found above
      $query->condition('node_field_data.nid', $typecastedResult, 'NOT IN');
    }
    return $query;
  }


  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['target_bundles']['#title'] = $this->t('Content types');
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    // Adding the 'node_access' tag is sadly insufficient for nodes: core
    // requires us to also know about the concept of 'published' and
    // 'unpublished'. We need to do that as long as there are no access control
    // modules in use on the site. As long as one access control module is there,
    // it is supposed to handle this check.
    if (!$this->currentUser->hasPermission('bypass node access') && !count($this->moduleHandler->getImplementations('node_grants'))) {
      $query->condition('status', NODE_PUBLISHED);
      $query->condition('type', 'boutique');
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
    $node = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);

    // In order to create a referenceable node, it needs to published.
    /** @var \Drupal\node\NodeInterface $node */
    $node->setPublished(TRUE);

    return $node;
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);
    // Mirror the conditions checked in buildEntityQuery().
    if (!$this->currentUser->hasPermission('bypass node access') && !count($this->moduleHandler->getImplementations('node_grants'))) {
      $entities = array_filter($entities, function ($node) {
        /** @var \Drupal\node\NodeInterface $node */
        return $node->isPublished();
      });
    }
    return $entities;
  }
}
