<?php

/**
 * @file
 * Contains materio_sapi.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Solarium\QueryType\Select\Query\Query;
use Drupal\search_api\Query\QueryInterface;
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_help().
 */
function materio_sapi_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the materio_sapi module.
    case 'help.page.materio_sapi':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Search Api Materio module') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_search_api_solr_query_alter();
 */
function materio_sapi_search_api_solr_query_alter(Query $solarium_query,  QueryInterface $query) {
  if ($termid = (int)$query->getOption('termid')) {
    // get solarium fileds name
    $index = $query->getIndex();
    $solrFields = $index->getServerInstance()
      ->getBackend()
      ->getSolrFieldNames($index);

    // tag_tid"itm_tag_tid"
    // thesaurus_tid"itm_thesaurus_tid"
    $tag_fname = $solrFields['tag_tid'];
    $thes_fname = $solrFields['thesaurus_tid'];
    // $solarium_query->addParam('bf', "recip(abs(ms(NOW,{$solrField})),3.16e-11,10,0.1)");
    // $bfparam = "if(or(gt(termfreq({$tag_fname},{$termid}),0),gt(termfreq({$thes_fname},{$termid}),0)),^21,0)";
    $bfparam = "if(or(exists(query({$tag_fname}:{$termid})),exists(query({$thes_fname}:{$termid}))),^21,0)";
    // boost=if(or(exists(query(itm_tag_tid:396)),exists(query(itm_thesaurus_tid:396))),^21,0 )
    $solarium_query->addParam('boost', $bfparam);
    // $solarium_query->addParam('debugQuery', 'on');
  }

}

/**
 * Prepares variables for fieldset element templates.
 *
 * Default template: fieldset.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
 *     Properties used: #attributes, #children, #description, #id, #title,
 *     #value.
 */
function materio_sapi_preprocess_fieldset(&$variables) {
  if (isset($variables['element']['#legend_attributes'])) {
    $variables['legend']['attributes'] = new Attribute($variables['element']['#legend_attributes']);
  }
}
