<?php

namespace Drupal\materio_sapi\Plugin\search_api\processor;

use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\user\UserInterface;

/**
 * Excludes unused terms from indexes.
 *
 * @SearchApiProcessor(
 *   id = "term_used",
 *   label = @Translation("Term used"),
 *   description = @Translation("Exclude unused taxonomy terms from being indexed."),
 *   stages = {
 *     "alter_items" = 0,
 *   },
 * )
 */
class TermUsed extends ProcessorPluginBase {

  /**
   * {@inheritdoc}
   */
  public static function supportsIndex(IndexInterface $index) {
    $interface = EntityPublishedInterface::class;
    foreach ($index->getDatasources() as $datasource) {
      $entity_type_id = $datasource->getEntityTypeId();
      if (!$entity_type_id) {
        continue;
      }
      // We support users and any entities that implement
      // \Drupal\Core\Entity\EntityPublishedInterface.
      if ($entity_type_id === 'taxonomy_term') {
        return TRUE;
      }
      // $entity_type = \Drupal::entityTypeManager()
      //   ->getDefinition($entity_type_id);
      // if ($entity_type && $entity_type->entityClassImplements($interface)) {
      //   return TRUE;
      // }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function alterIndexedItems(array &$items) {
    // Annoyingly, this doc comment is needed for PHPStorm. See
    // http://youtrack.jetbrains.com/issue/WI-23586
    /** @var \Drupal\search_api\Item\ItemInterface $item */
    foreach ($items as $item_id => $item) {
      $term = $item->getOriginalObject()->getValue();
      $enabled = TRUE;
      // $entity_storage = \Drupal::entityTypeManager()->getStorage('node');
      // $count_query = $entity_storage->getQuery()
      //   ->condition('type', 'materiau')
      //   ->accessCheck(TRUE)
      //   ->condition('status', '1')
      //   ->count();
      //
      // $this->count = $this->count_query->execute();
      $query = \Drupal::database()->select('taxonomy_index', 'ti');
      $query->fields('ti', array('nid'));
      $query->condition('ti.tid', $term->id());
      $query->distinct(TRUE);
      $result = $query->execute();
      $nodeIds = $result->fetchCol();
      if (!$nodeIds) {
        unset($items[$item_id]);
      }
    }
  }

}
