<?php

namespace Drupal\nodehive_core\Plugin\CalendarFilter;

use Drupal\content_calendar\Plugin\CalendarFilterPluginBase;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

/**
 * Content type calendar filter.
 *
 * @CalendarFilterPlugin(
 *   id = "space",
 *   label = @Translation("Space"),
 *   weight = 2,
 *   query_id = "space"
 * )
 */
class Space extends CalendarFilterPluginBase implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $definition = $this->getPluginDefinition();
    $filter_settings = $this->getSettings();

    if (!$filter_settings['enable']) {
      return;
    }

    $widget = $this->filterWidgetPluginManager()
      ->createInstance(
        $filter_settings['widget']
    );

    $build = $widget->build([
      'id' => $this->getPluginId(),
      'label' => $definition['label'],
      'query_key' => $definition['query_id'],
      'options' => $this->getSpaces(),
    ]);
    $build['#weight'] = $definition['weight'];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function alterQuery(SelectInterface $query, $value) {
    $space_ids = explode(",", $value);

    $field_table_name = "node__nodehive_space";
    $alias = "ns";

    $query->innerJoin(
      $field_table_name,
      $alias,
      'nfd.nid = ' . $alias . '.entity_id'
    );

    $query->condition($alias . '.nodehive_space_target_id', $space_ids, "IN");

    return $query;
  }

  /**
   * Get all spaces.
   *
   * @return array
   *   Returns an array with display options.
   */
  protected function getSpaces() {
    $options = [];

    $spaces = $this->entityTypeManager()
      ->getStorage('nodehive_space')
      ->loadMultiple();

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

    return $options;
  }

}
