<?php

namespace ggbn;

use Yii;
use Solarium;

/*
 * This QueryManager handles all SOLR-Queries
 */
class SOLRQueryManager {
	
	// place here all queries for the field results:
	// use the correct field var names of the index doc (should match with model field)!
	public static function getPartialQuery($field, $value, $filters, $details) {
		// echo "getPartialQuery";
		switch ($field) {
			case 'fullScientificName' :
				return $field . '_nc:' . $value . '';
				break;
			case 'kingdom' :
				if ($value == "Not\ assigned")
					return '(regnum:' . $value . ' OR regnum:N/A OR regnum:null)';
				else
					return 'regnum:' . $value . '';
				break;
			case 'phylumName' :
				if ($value == "Not\ assigned")
					return '(phylum:' . $value . ' OR phylum:N/A OR phylum:null)';
				else
					return 'phylum:' . $value . '';
				break;
			case 'orderName' :
				if ($value == "Not\ assigned")
					return '(ordo:' . $value . ' OR ordo:N/A OR ordo:null)';
				else
					return 'ordo:' . $value . '';
				break;
			case 'familyName' :
				if ($value == "Not\ assigned")
					return '(familia:' . $value . ' OR familia:N/A OR familia:null)';
				else
					return 'familia:' . $value . '';
				break;
			case 'className' :
				if ($value == "Not\ assigned")
					return '(classis:' . $value . ' OR classis:N/A OR classis:null)';
				else
					return 'classis:' . $value . '';
				break;
			case 'geneticlocus' :
				return $field . ':"' . $value . '"';
				break;
			case 'collectioncode' :
				return $field . ':"' . $value . '"';
				break;
			case 'institutioncode' :
				return $field . ':"' . $value . '"';
				break;
				return $field . ':"' . $value . '"';
				break;
			case 'locality' :
				return $field . ':"' . $value . '"';
				break;
			case 'collectors' :
				return $field . ':*' . $value . '*';
				break;
			case 'collectornumber' :
				return $field . ':*' . $value . '*';
				break;
			case 'cites' :
				if ($value == "include")
					return "citesStatus:*";
				if ($value == "exclude")
					return "citesStatus:N/A";
				if ($value == "citesOnly")
					return "citesStatus:I*";
				break;
			case 'sequenceaccessionIdentifier' :
				return $field . ':' . $value . '*';
				break;
			case 'unitID' :
				// case 'sample' :
				if ($value == '*') {
					return 'unitID:*';
				} else {
					// if (! isset ( $_GET ['collectioncode'] ) or $_GET ['collectioncode'] != "") {
					// return $field . ':"' . $value . '"';
					// } else {
					if ($details)
						return '(' . $field . ':"' . $value . '" OR unitaccessionnumber:' . $value . ' OR trick17ID:' . $value . ')';
					else
						return '(' . $field . ':"' . $value . '" OR unitaccessionnumber_nc:' . $value . ' OR trick17ID:' . $value . ')';
					// return '(' . $field . ':"' . $value . '" OR unitaccessionnumber:"' . $value . '"*)';
					// }
				}
				// return "country:Germany"; }
				;
				break;
			case 'hasImage' :
			case 'hasTypestatus' :
				if ($value == 1) {
					return $field . ":" . $value;
				} else {
					return false;
				}
				break;
			// lists
			// they alway deliver a value so we have to check
			// if it is the "nothing choosen value"
			// then we won't need a query
			case 'country' :
				return $field . ":" . $value;
				break;
			case 'recordbasis' :
				return $field . ":" . $value;
				break;
			case 'isocountrycode' :
				return $field . ":" . $value;
				break;
			case 'continent' :
				return $field . ":" . $value;
				break;
			case 'sea' :
				return $field . ":" . $value;
				break;
			case 'ocean' :
				return $field . ":" . $value;
				break;
			case 'sampletype' :
				return $field . ":" . $value;
				break;
			case 'institution' :
				// if ($value == $model->getSelectionListNonChosen () or $value == '0') {
				if ($value == "---" or $value == '0') { // Gabis Version
					return false;
				} else {
					return $field . ":\"" . $value . "\"";
				}
				break;
			// fields with that come as a pair and provide a range for the value
			case 'latitudeFrom' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleCoordinates ( $filters );
				break;
			case 'latitudeTo' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleCoordinates ( $filters );
				break;
			
			case 'longitudeFrom' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleCoordinates ( $filters );
				break;
			case 'longitudeTo' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleCoordinates ( $filters );
				break;
			case 'collectionYearFrom' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleYear ( $filters );
				break;
			// collection year
			case 'collectionYearTo' :
				// TODO this has to go to form validation!!!
				return SOLRQueryManager::handleYear ( $filters );
				break;
			default : // this should never happen
				return $field . ":" . $value;
				break;
		}
		// return $query[$field];
	}
	static function handleCoordinates($filters) {
		$latf = NULL;
		$latt = NULL;
		$longf = NULL;
		$longt = NULL;
		if (isset ( $filters ['latitudeTo'] ))
			$latt = str_replace ( ",", ".", $filters ['latitudeTo'] );
		if (isset ( $filters ['latitudeFrom'] ))
			$latf = str_replace ( ",", ".", $filters ['latitudeFrom'] );
		if (isset ( $filters ['longitudeFrom'] ))
			$longf = str_replace ( ",", ".", $filters ['longitudeFrom'] );
		if (isset ( $filters ['longitudeTo'] ))
			$longt = str_replace ( ",", ".", $filters ['longitudeTo'] );
		
		if ($latf == NULL && $latt == NULL) {
			$latf = - 90;
			$latt = 90;
		} elseif ($latf == NULL && $latt != NULL) {
			$latf = $latt - 0.10;
			$latf = - 90;
		} elseif ($latf != NULL && $latt == NULL) {
			$latt = $latf + 0.10;
			$latt = 90;
		}
		
		if ($longf == NULL && $longt == NULL) {
			$longf = - 180;
			$longt = 180;
		} elseif ($longf == NULL && $longt != NULL) {
			$longf = $longt - 0.10;
			$longf = - 180;
		} elseif ($longf != NULL && $longt == NULL) {
			$longt = $longf + 0.10;
			$longt = 180;
		}
		
		return "coordinates:[" . $latf . "," . $longf . " TO " . $latt . "," . $longt . "]";
	}
	static function handleYear($filters) {
		$yearf = 0;
		$yeart = date ( 'Y' );
		if (isset ( $filters ['collectionYearFrom'] ))
			$yearf = str_replace ( ",", ".", $filters ['collectionYearFrom'] );
		if (isset ( $filters ['collectionYearTo'] ))
			$yeart = str_replace ( ",", ".", $filters ['collectionYearTo'] );
		
		return "gatheringyear:[" . $yearf . " TO " . $yeart . "]";
	}
	public static $client;
	/**
	 * this fun creates an index query for the search request
	 *
	 * @param unknown $model        	
	 * @param unknown $selectionLists        	
	 * @param number $pageSize        	
	 * @return SolrQuery - if any value in the form was set, else return false
	 */
	public static function createSearchQuery($config) {
		
		// create a client instance
		SOLRQueryManager::$client = new Solarium\Client ( $config );
		// set the adapter to http
		SOLRQueryManager::$client->setAdapter ( 'Solarium\Core\Client\Adapter\Http' );
		
		// get a select query instance
		$query = SOLRQueryManager::$client->createSelect ();
		
		return $query;
	}
	public static function fillAndExecuteQuery($query, $queryString, $fq, $filters, $details) {
// 		Yii::info ( "fillAndExecuteQuery " . $queryString . " and fq: " . $fq );
		
		// foreach ( $filters as $k => $v )
		// Yii::info ( "fillAndExecuteQuery request param " . $k . ", " . $v );
		
		$query->setQuery ( $queryString );
		// Note: SOLR starts counting with row 0, page 2 needs to start with row 50 not 51!
		if (isset ( $_GET ['page'] )) {
			$query->setStart ( Yii::$app->params ['listPerPage'] * ($_GET ['page'] - 1) );
		} else {
			$query->setStart ( 0 );
		}
		
		$query->setRows ( Yii::$app->params ['maxLines'] );
		$filterq = [ ];
		if (isset ( $filters )) {
			if (sizeof ( $filters ) == 0)
				$query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
			else
				foreach ( $filters as $key => $value ) {
// 					Yii::info ( "hop " . $key . "---" . $value );
					$value = str_replace ( " ", "\ ", $value );
					$value = str_replace ( "(", "\(", $value );
					$value = str_replace ( ")", "\)", $value );
					$value = str_replace ( ":", "\:", $value );
					$filterq [] = SOLRQueryManager::getPartialQuery ( $key, $value, $filters, $details );
					
					// Yii::info ( "filterquery " . $filterq );
					
					// }
				}
		}
		if (isset ( $filterq )) {
			$query->createFilterQuery ( 'myfilter_' )->setQuery ( $fq . implode ( " AND ", $filterq ) );
		}
		
		$debug = $query->getDebug ();
		
		$resultset = SOLRQueryManager::$client->select ( $query );
		$debugResult = $resultset->getDebug ();
		
// 		Yii::info ( 'Querystring: ' . $debugResult->getParsedQuery () );
// 		Yii::info ( 'NumFound: ' . $resultset->getNumFound () );
		return $resultset;
	}
	public static function browseQuery($query, $queryString, $fqs, $page, $facetNames) {
 		Yii::info ( "browseQuery " . $queryString  );
		
		$query->setQuery ( $queryString );
		// Note: SOLR starts counting with row 0, page 2 needs to start with row 50 not 51!
		if ($page) {
			$query->setStart ( $page - 1 )->setRows ( Yii::$app->params ['listPerPage'] );
		} else {
			$query->setStart ( 0 )->setRows ( Yii::$app->params ['listPerPage'] );
		}
		
		$facetSet = $query->getFacetSet ();
		$facetSet->setLimit ( - 1 );
		$facetSet->setMinCount ( 1 );
		$facetSet->setSort ( "false" );
		
		$filtering = $fqs;
		
		$i = 0;
		if (sizeof ( $fqs ) > 0) {
			foreach ( $fqs as $fq ) {
				$query->createFilterQuery ( 'myfilter' . $i )->setQuery ( $fq );
				foreach ( $facetNames as $fname )
					if (sizeof ( explode ( $fname, $fq, - 1 ) ) > 0) {
						$facetSet->createFacetQuery ( $fname . $i )->setQuery ( $filtering [$i] );
					}
				$i ++;
			}
		} else {
			$fq = "*:*";
			$query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
		}
		
		// create a facet field instance and set options
		foreach ( $facetNames as $fname )
			$facetSet->createFacetField ( $fname )->setField ( $fname );
		
		$resultset = SOLRQueryManager::$client->select ( $query );
		
		return $resultset;
	}
	public static function treeQuery($query, $queryString, $fname) {
// 		Yii::info ( "treeQuery " . $queryString );
		
		$query->setQuery ( $queryString );
		$query->setStart ( 0 )->setRows ( Yii::$app->params ['listPerPage'] );
		
		$facetSet = $query->getFacetSet ();
		$facetSet->setLimit ( - 1 );
		$facetSet->setMinCount ( 1 );
		$facetSet->setSort ( "false" );
		
		$fq = "*:*";
		$query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
		
		// create a facet field instance and set options
		$facetSet->createFacetField ( $fname )->setField ( $fname );
		
		$resultset = SOLRQueryManager::$client->select ( $query );
		
		return $resultset;
	}
	
	/**
	 *
	 * @param SolrQuery $criteria        	
	 * @return SolrObject
	 */
	public static function getConfigDetails() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => Yii::$app->params ['solrdetails'] 
						) 
				) 
		);
		return $config;
	}
	public static function getConfigCore() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => Yii::$app->params ['solrcore'] 
						) 
				) 
		);
		return $config;
	}
	public static function getConfigStats() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => Yii::$app->params ['solrstats'] 
						) 
				) 
		);
		return $config;
	}
	public static function getConfigBackbone() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => '/solr/backbone' 
						) 
				) 
		);
		return $config;
	}
	public static function getConfigColTree() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => '/solr/colTree' 
						) 
				) 
		);
		return $config;
	}
	public static function getConfigWebsites() {
		$config = array (
				'endpoint' => array (
						'bgbm-web01' => array (
								'host' => Yii::$app->params ['solrhost'],
								'port' => 8080,
								'path' => Yii::$app->params ['solrwebsites'] 
						) 
				) 
		);
		return $config;
	}
}
?>