<?php

namespace common\models;

use Yii;
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 "g.droege"
 *        
 */
class FormSelectionQueryManager {
	
	/**
	 * this fun creates the selection list of the field $field
	 *
	 * @param unknown $field        	
	 * @param string $nonChosenString        	
	 * @return multitype:
	 */
	public static function newList($field, $nonChosenString = "---") {
// 		Yii::info ( "build List for fild " . $field );
		// fetch the values from the response:
		$selectionArray = array ();
		array_push ( $selectionArray, $nonChosenString );
		
		$resultLowestUnit = FormSelectionQueryManager::getListLowest ( $field, $nonChosenString = "---" );
		
		foreach ( $resultLowestUnit as $doc => $count ) {
			// Trick 17 :))
			if ($doc != "N/A" && $doc != "institutionName, CityName") { // "N/A" always in index ifnull in MySQL-DB -> hide in portal
				array_push ( $selectionArray, $doc . " (" . $count . ")" );
			}
		}
		
		sort ( $selectionArray, SORT_STRING );
		return $selectionArray;
	}
	public static function buildList($field, $nonChosenString = "---") {
// 		Yii::info ( "build List for fild " . $field );
		// fetch the values from the response:
		$selectionArray = array ();
		array_push ( $selectionArray, $nonChosenString );
		
		$resultLowestUnit = FormSelectionQueryManager::getList ( $field, $nonChosenString = "---" );
		
		foreach ( $resultLowestUnit as $doc => $count ) {
			// Trick 17 :))
			if ($doc != "N/A" && $doc != "institutionName, CityName") { // "N/A" always in index ifnull in MySQL-DB -> hide in portal
				array_push ( $selectionArray, $doc . " (" . $count . ")" );
			}
		}
		
		sort ( $selectionArray, SORT_STRING );
		return $selectionArray;
	}
	public static function getList($field, $nonChosenString = "---") {
// 		Yii::info ( "get lowest element for the list " . $field );
		$config =SOLRQueryManager::getConfigSearch();
		// Yii::info("Yii::app->params ['solrhost'] ".Yii::$app->params ['solrhost']);
		
		// create a client instance
		$client = new Solarium\Client ( $config );
		// set the adapter to http
		$client->setAdapter ( 'Solarium\Core\Client\Adapter\Http' );
		
		// get a select query instance
		$query = $client->createSelect ();
		// set fields to fetch (this overrides the default setting 'all fields')
		$query->setFields ( [ 
				"[]" 
		] );
		
		$fsolr = $field;
		if ($field === "kingdom")
			$fsolr = "regnum";
		
		$query->setQuery ( $fsolr . ":* AND isLowest:1" );
		// $fq = "{!join from=lowestTripleIDs to=tripleidstoreid fromIndex=".Yii::$app->params ['solrsearch']."}".$fsolr . ":*";
		// Yii::info("FQ? ".$fq);
		// $query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
		// get the facetset component
		try {
			$facetSet = $query->getFacetSet ();
		} catch ( Solarium\Exception\UnexpectedValueException $e ) {
			$facetSet = $query->getFacetSet ();
		}
		$facetSet->setLimit ( - 1 );
		$facetSet->setMinCount ( 1 );
		$facetSet->setSort ( "false" );
		
		// create a facet field instance and set options
		$facetSet->createFacetField ( $fsolr )->setField ( $fsolr );
		
		// this executes the query and returns the result
		$raw_response = $client->select ( $query );
		try {
			$result = $raw_response->getFacetSet ()->getFacet ( $fsolr );
		} catch ( Solarium\Exception\UnexpectedValueException $e ) {
			$result = $raw_response->getFacetSet ()->getFacet ( $fsolr );
		}
		$resultLowestUnit = [ ];
		foreach ( $result as $doc => $count ) {
			$resultLowestUnit [$doc] = $count;
			// Yii::info("SUBLIST: ".$doc);
		}
		return $resultLowestUnit;
	}
	public static function getListLowest($field, $nonChosenString = "---") {
// 		Yii::info ( "get lowest element for the list " . $field );
		$config =SOLRQueryManager::getConfigSearch();
		// Yii::info("Yii::app->params ['solrhost'] ".Yii::$app->params ['solrhost']);
		
		// create a client instance
		$client = new Solarium\Client ( $config );
		// set the adapter to http
		$client->setAdapter ( 'Solarium\Core\Client\Adapter\Http' );
		
		// get a select query instance
		$query = $client->createSelect ();
		// set fields to fetch (this overrides the default setting 'all fields')
		$query->setFields ( [ 
				"[]" 
		] );
		$query->setRows(0);
		
		$fsolr = $field;
		if ($field === "kingdom")
			$fsolr = "regnum";
		
		if ($field == "voucherCol") {
		$query->setQuery ( $fsolr . ":* AND (sampletype:specimen OR sampletype:eVoucher OR sampletype:culture OR sampletype:unknown)" ); }
		else { 
		$query->setQuery ( $fsolr . ":* AND isLowest:1".Yii::$app->params['thematicSOLRfilter'] ); }
		//$query->addParam("tripleidstoreid","lowestTripleIDs");
		//$fq = "{!join from=lowestTripleIDs to=tripleidstoreid fromIndex=" . Yii::$app->params ['solrsearch'] . "}" . $fsolr . ":*";
// 		$fq =""; //dont need fq
// 		// Yii::info("FQ? ".$fq);
// 		$query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
		// get the facetset component
		try {
			$facetSet = $query->getFacetSet ();
		} catch ( Solarium\Exception\UnexpectedValueException $e ) {
			$facetSet = $query->getFacetSet ();
		}
		$facetSet->setLimit ( - 1 );
		$facetSet->setMinCount ( 1 );
		$facetSet->setSort ( "false" );
		
		// create a facet field instance and set options
		$facetSet->createFacetField ( $fsolr )->setField ( $fsolr );
		
		// this executes the query and returns the result
		try {
			$raw_response = $client->select ( $query );
		} catch ( Solarium\Exception\UnexpectedValueException $e ) {
			$raw_response = $client->select ( $query );
		}
		$result = $raw_response->getFacetSet ()->getFacet ( $fsolr );
		$resultLowestUnit = [ ];
		foreach ( $result as $doc => $count ) {
			$resultLowestUnit [$doc] = $count;
			// Yii::info("SUBLIST: ".$doc);
		}
		return $resultLowestUnit;
	}
	
	/**
	 * creates all lists for the suggestion fields
	 * these lists are static and do not change on the users behaviour
	 *
	 * @param array(string) $listNames        	
	 * @param string $nonChosenString        	
	 * @return array(array(string) list of the selection lists
	 */
	public static function getAllLists($listNames, $nonChosenString = "---") {
		$allFormSelectionLists = array ();
		foreach ( $listNames as $name ) {
			try {
				$list = FormSelectionQueryManager::newList ( $name, $nonChosenString );
				$allFormSelectionLists [$name] = $list;
			} catch ( \Solarium\Exception\HttpException $e ) {
				$allFormSelectionLists [$name] = [ 
						'coming soon' 
				];
			}
		}
		return $allFormSelectionLists;
	}
	public static function getSelectionLists($listNames, $nonChosenString = "---") {
		$allFormSelectionLists = array ();
		foreach ( $listNames as $name ) {
			try {
				$list = FormSelectionQueryManager::buildList ( $name, $nonChosenString );
				$allFormSelectionLists [$name] = $list;
			} catch ( \Solarium\Exception\HttpException $e ) {
				$allFormSelectionLists [$name] = [ 
						'coming soon' 
				];
			}
		}
		return $allFormSelectionLists;
	}
}

?>