<?php

/**
 * @file
 * Search API Solr compatibility helpers.
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\search_api\Entity\Server;
use Drupal\search_api_solr\Hook\SearchApiSolrHooks;
use Drupal\search_api_solr\SolrBackendInterface;

/**
 * Get the default third party settings of an index for Solr.
 *
 * @return array
 *   Third party settings array.
 */
function search_api_solr_default_index_third_party_settings() {
  return SearchApiSolrHooks::defaultIndexThirdPartySettings();
}

/**
 * Merges the default third party settings to those of an index for Solr.
 *
 * @param array $third_party_settings
 *   Third party settings array.
 *
 * @return array
 *   Third party settings array.
 */
function search_api_solr_merge_default_index_third_party_settings(array $third_party_settings) {
  return SearchApiSolrHooks::mergeDefaultIndexThirdPartySettings($third_party_settings);
}

/**
 * Preserves index third-party settings that are not exposed by the form.
 *
 * @param string $entity_type_id
 *   The entity type ID.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity updated with the submitted values.
 * @param array $form
 *   The complete form array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current form state.
 */
function search_api_solr_search_api_index_form_entity_builder($entity_type_id, EntityInterface $entity, array &$form, FormStateInterface $form_state): void {
  SearchApiSolrHooks::searchApiIndexFormEntityBuilder($entity_type_id, $entity, $form, $form_state);
}

/**
 * Form validation.
 *
 * @param array $element
 *   The form element.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The form state.
 * @param array $form
 *   The form array.
 *
 * @throws \Drupal\search_api\SearchApiException
 */
function search_api_solr_form_search_api_index_form_validate_server(array &$element, FormStateInterface $form_state, array $form) {
  if ($server = Server::load($form_state->getValue('server'))) {
    if ($server->getBackend() instanceof SolrBackendInterface) {
      /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
      $form_object = $form_state->getFormObject();
      $this_index = $form_object->getEntity();
      $indexes = $server->getIndexes();
      $index_count = 0;
      foreach ($indexes as $index) {
        if ($index->status()) {
          if (!$this_index->isNew() && ($this_index->id() == $index->id())) {
            continue;
          }
          ++$index_count;
        }
      }
      if ($index_count > 0 && $form_state->getValue('status')) {
        \Drupal::messenger()->addWarning(
          new TranslatableMarkup("You're storing multiple indexes on the same Solr index (aka core). Take care if you use advanced Solr features like spell checking, suggesters, terms, autocomplete and others directly, because they aren't aware of these multiple indexes by default. Use Search API family modules like Autocomplete module instead which will help you to avoid issues.")
        );
      }
    }
  }
}

/**
 * Re-install all default Solr Field Types from their yml files.
 */
function search_api_solr_install_missing_field_types() {
  \Drupal::moduleHandler()->loadInclude('search_api_solr', 'install');
  search_api_solr_update_helper_install_configs();
}

/**
 * Get all Search API servers that use a Solr backend.
 *
 * @param bool $only_active
 *   Whether to only return active servers or all.
 *
 * @return \Drupal\search_api\ServerInterface[]
 *   The servers.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 * @throws \Drupal\search_api\SearchApiException
 */
function search_api_solr_get_servers($only_active = TRUE) {
  $solr_servers = [];
  $storage = \Drupal::entityTypeManager()->getStorage('search_api_server');
  /** @var \Drupal\search_api\ServerInterface[] $servers */
  $servers = $only_active ? $storage->loadByProperties(['status' => TRUE]) :
    $storage->loadMultiple();
  foreach ($servers as $server) {
    if (
      $server->hasValidBackend() &&
      $server->getBackend() instanceof SolrBackendInterface
    ) {
      $solr_servers[$server->id()] = $server;
    }
  }
  return $solr_servers;
}

/**
 * Returns visibility state status values.
 *
 * @return array
 *   Options array.
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 * @throws \Drupal\search_api\SearchApiException
 */
function _search_api_solr_visibility() {
  $valid_option = [];
  foreach (search_api_solr_get_servers(FALSE) as $server) {
    $valid_option[] = [
      'value' => $server->id(),
    ];
  }
  return $valid_option;
}
