<?php

namespace ggbn;

use Yii;
use yii\log\Logger;
use Solarium;

/**
 * we collect all content possibilities from the
 * $field
 * of the index to provide a selection list for the search form.
 *
 * eg. with $field="country"
 * we get a list of all countries that are used.
 *
 * @author "s.buers"
 *        
 */
class FormSuggestionsQueryManager {
	
	static function getHierarchy($name) {
		// create a client instance
		$client = new Solarium\Client ( SOLRQueryManager::getConfigSearch());
		// set the adapter to http
		$client->setAdapter ( 'Solarium\Core\Client\Adapter\Http' );
		// get a select query instance
		$query = $client->createSelect ();
		
		// set a query (all prices starting from 12)
		$query->setQuery ( 'fullScientificName:' . str_replace ( ")", "\)", str_replace ( ":", "\:", str_replace ( "(", "\(", str_replace ( " ", "\ ", $name ) ) ) ) );
		
		// set fields to fetch (this overrides the default setting 'all fields')
		$query->setFields ( array (
				'hierarchy,backbonefullname,backboneaccepted,backboneref' 
		) );
		
		// this executes the query and returns the result
		$resultset = $client->select ( $query );
		foreach ( $resultset as $document ) {
			try {
				$fn = $document->backbonefullname;
				$fn = str_ireplace ( " ", "", $fn );
				$fn = str_ireplace ( ".", "", $fn );
				$fn = str_ireplace ( "(", "", $fn );
				$fn = str_ireplace ( ")", "", $fn );
				$ba = $document->backboneaccepted;
				$ba = str_ireplace ( " ", "", $ba );
				$ba = str_ireplace ( ".", "", $ba );
				$ba = str_ireplace ( "(", "", $ba );
				$ba = str_ireplace ( ")", "", $ba );
				if (! Yii::$app->params ['noBack'])
					if ($ba !== $fn) {
						$accepted = $document->backbonefullname . " is " . $document->backboneaccepted . " according to " . $document->backboneref;
						return [ 
								$document->hierarchy,
								$document->backboneaccepted,
								$accepted 
						];
					} else if (! empty ( $ba )) {
						return [ 
								$document->hierarchy,
								$document->backboneaccepted 
						];
					} else {
						return [ 
								"no backbone hit",
								$name 
						];
					}
				else {
					if ($ba !== $fn) {
						$accepted = " is a synonym of " . $document->backboneaccepted . " according to " . $document->backboneref;
						return [ 
								$document->hierarchy,
								$name,
								$accepted 
						];
					} else if (! empty ( $ba )) {
						$accepted = " is accepted according to " . $document->backboneref;
						return [ 
								$document->hierarchy,
								$document->backboneaccepted,
								$accepted 
						];
					} else
						return [ 
								" ",
								$name,
								"was not found in The Plant List" 
						]
						;
				}
			} catch ( Exception $e ) {
				return [ 
						$document->hierarchy,
						$document->backboneaccepted 
				];
			}
			return [ 
					$document->hierarchy,
					$document->backboneaccepted 
			];
		}
		
		return [ ];
	}
	/**
	 * this builds a query for an autosuggest field
	 * it is used dynamically
	 * (depending on the user input)
	 * and runs the query and returns the result
	 */
	public static function newFacetsList($field, $filter, $filteropt) {
		// create a client instance
		$client = new Solarium\Client ( SOLRQueryManager::getConfigSearch() );
		
		// set the adapter to http
		$client->setAdapter ( 'Solarium\Core\Client\Adapter\Http' );
		
		// get a select query instance
		$query = $client->createSelect ();
		
		// get the facetset component
		$facetSet = $query->getFacetSet ();
		
		// set fields to fetch (this overrides the default setting 'all fields')
		$query->setFields ( array (
				$field 
		) );
		$facetSet->setLimit ( - 1 );
		$facetSet->setMinCount ( 1 );
		$facetSet->setSort ( "false" );
		
		// set a query
		// $query->setQuery ( $field_suggest . ":" . $filter . "*" );
// 		if($field=='sequenceaccessionIdentifier')
// 			$suffix='';
// 		else $suffix ="_nc";
		$suffix ="_nc";
		if (isset ( $filteropt ) && ! empty ( $filteropt ))
			$query->setQuery ( $field . $suffix.":" . $filter . "* AND " . $filteropt );
		else
			$query->setQuery ( $field . $suffix.":" . $filter . "*" );
		
		$facet = $facetSet->createFacetMultiQuery ( $field . '2' );
		$facet->createQuery ( $field, $field .  $suffix.':' . $filter . '*' );
		$facetSet->createFacetField ( $field )->setField ( $field );
		
		// this executes the query and returns the result
		$resultset = $client->select ( $query );
		
		$result = array ();
		// display facet query count
		$facet = $resultset->getFacetSet ()->getFacet ( $field );
		$nbElts = 0;
		foreach ( $facet as $key => $count ) {
			if ($nbElts > 10) {
				ksort ( $result );
				return $result;
			}
			if ($count > 0) {
				if ($field != "fullScientificName"){
// 					Yii::info("stripos " .stripos($key, $filter));
					if( (stripos($key, $filter))!==false)
					$result [$key] = $count;
				}
				if ($field == "fullScientificName") {
					$tmp = FormSuggestionsQueryManager::getHierarchy ( $key );
					$ba = str_ireplace ( " ", "", $tmp [1] );
					$ba = str_ireplace ( ".", "", $ba );
					$ba = str_ireplace ( "(", "", $ba );
					$ba = str_ireplace ( ")", "", $ba );
					$n = str_ireplace ( " ", "", $key );
					$n = str_ireplace ( ".", "", $n );
					$n = str_ireplace ( "(", "", $n );
					$n = str_ireplace ( ")", "", $n );
					if ($ba != $n)
						$key = $tmp [1];
					$result [$key] = $count;
					$result ["hierarchy" . $key] = $tmp [0];
					$nbElts ++;
					if (sizeof ( $tmp ) == 3) {
						$result ["reason" . $key] = $tmp [2];
						$nbElts += 0.5;
					}
					// Yii::info ( "result [key]" . $key );
					// Yii::info ( "result [hierarchy . key]" . $result ["hierarchy" . $key] );
					// Yii::info ( "result [acceptedName . key]" . $result ["acceptedName" . $key] );
				}
			}
		}
		
		ksort ( $result );
		return $result;
	}
}

?>