<?php
/*
 * 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)!
	private static function getPartialQuery($field, $value, $model) {
		switch ($field) {
			case 'fullScientificName' :
				$last = substr ( $value, - 1, 1 );
				$test = strlen ( $value );
				$count = $test - 1;
				$search = substr ( $value, 0, $count );
				if ($last == '*' and $test > 1) {
					$value = $search;
					return $field . ':"' . $value . '"*';
				}
				if ($last != '*') {
					return $field . ':"' . $value . '"';
				}
				;
				break;
			case 'familyName' :
			case 'geneticlocus' :
			case 'collectioncode' :
			case 'institutioncode' :
				return $field . ':"' . $value . '"';
				;
				break;
			case 'locality' :
			case 'collectors' :
			case 'collectornumber' :
				return $field . ':*' . $value . '*';
				;
				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 {
						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' :
			case 'isocountrycode' :
			case 'continent' :
			case 'sea' :
			case 'ocean' :
			case 'sampletype' :
			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!!!
				$value2;
				if (floatval ( $value )) {
					if (floatval ( $model->attributes ['latitudeTo'] )) {
						$value2 = $model->attributes ['latitudeTo'];
						// TODO: build query string
						// blank latitudeTo because it is already considered here
						// and needed not be used for an other query
						$model->attributes = array (
								'latitudeTo' => '' 
						);
						
						// if only from is set
					} else {
						$value2 = "*";
					}
					return "latitude:[" . $value . " TO " . $value2 . "]";
				} 

				else {
					// TODO remove when yii validation is doing this
					return false;
				}
				break;
			case 'latitudeTo' :
				// TODO this has to go to form validation!!!
				if (floatval ( $value )) {
					// this is only the case when "to" is set but not "from"
					// the other cases are already covered in the longitudeFrom case
					if (! (floatval ( $model->attributes ['latitudeFrom'] ))) {
						return "latitude:[ * TO " . $value . "]";
						// if only from is set
					}
				}
				return false;
				break;
			
			case 'longitudeFrom' :
				// TODO this has to go to form validation!!!
				$value2;
				if (floatval ( $value )) {
					if (floatval ( $model->attributes ['longitudeTo'] )) {
						$value2 = $model->attributes ['longitudeTo'];
						// TODO: build query string
						// blank latitudeTo because it is already considered here
						// and needed not be used for an other query
						$model->attributes = array (
								'longitudeTo' => '' 
						);
						
						// if only from is set
					} else {
						$value2 = "*";
					}
					return "longitude:[" . $value . " TO " . $value2 . "]";
				} 

				else {
					// TODO remove when yii validation is doing this
					return false;
				}
				break;
			case 'longitudeTo' :
				// TODO this has to go to form validation!!!
				if (floatval ( $value )) {
					// this is only the case when "to" is set but not "from"
					// the other cases are already covered in the longitudeFrom case
					if (! (floatval ( $model->attributes ['longitudeFrom'] ))) {
						return "longitude:[ * TO " . $value . "]";
						// if only from is set
					}
				}
				
				return false;
				break;
			case 'collectionYearFrom' :
				// TODO this has to go to form validation!!!
				$value2;
				if (floatval ( $value )) {
					if (floatval ( $model->attributes ['collectionYearTo'] )) {
						$value2 = $model->attributes ['collectionYearTo'];
						// TODO: build query string
						// blank collectionYearTo because it is already considered here
						// and needed not be used for an other query
						$model->attributes = array (
								'collectionYearTo' => '' 
						);
						
						// if only from is set
					} else {
						$value2 = "*";
					}
					return "gatheringyear:[" . $value . " TO " . $value2 . "]";
				} 

				else {
					// TODO remove when yii validation is doing this
					return false;
				}
				break;
			// collection year
			case 'collectionYearTo' :
				// TODO this has to go to form validation!!!
				if (floatval ( $value )) {
					// this is only the case when "to" is set but not "from"
					// the other cases are already covered in the collectionYearFrom case
					if (! (floatval ( $model->attributes ['collectionYearFrom'] ))) {
						return "gatheringyear:[ * TO " . $value . "]";
						// if only from is set
					}
				}
				
				return false;
				break;
			default : // this should never happen
			          // TODO error handling
				return false;
				break;
		}
		// return $query[$field];
	}
	
	/**
	 * 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($model, $selectionlists) {
		$doQuery = false;
		
		// ---------- preparations before composing the query ---------
		
		$criteria = new ASolrCriteria ();
		$criteria->query = "*:*";
		
		// Note: SOLR starts counting with row 0, page 2 needs to start with row 50 not 51!
		if (isset ( $_GET ['page'] )) {
			$criteria->setStart ( Yii::app ()->params ['listPerPage'] * ($_GET ['page'] - 1) );
		} else {
			$criteria->setStart ( 0 );
		}
		
		$criteria->setRows ( Yii::app ()->params ['listPerPage'] ); // defined in global params
		                                                        // $criteria->setParam ('sort', 'fullScientificName asc');
		
		foreach ( $model->attributes as $k => $v )
			Yii::log ( "fillAndExecuteQuery request param " . $k . ", " . $v, "1", "app" );
			
			// create the query
			// take the values from the form and add a query for them
			// if they are not empty (filled in by the user)
		foreach ( $model->attributes as $key => $value ) {
			if (str_replace ( " ", "", $value ) != "") {
				
				// Yii::app()->request->cookies[$key] = new CHttpCookie($key, $value); //Gabi hinzugefügt um Cookies zu erzeugen ; erstmal rausgenommen
				// $fq = "{!join+from=lowestTripleIDs+to=fk_tripleidstoreid+fromIndex=ggbn_core}";
				
				$fq = "{!join from=lowestTripleIDs to=fk_tripleidstoreid fromIndex=ggbn_core}" . SOLRQueryManager::getPartialQuery ( $key, $value, $model );
				
				if ($fq) {
					$criteria->addFilterQuery ( $fq );
					
					$doQuery = true;
				}
			}
		}
		
		if ($doQuery) {
			return $criteria;
		} else
			return false;
	}
	
	/**
	 *
	 * @param SolrQuery $criteria        	
	 * @return SolrObject
	 */
	public static function getQueryResponseDetails($criteria, $model) {
		$query_response = Yii::app ()->solr_details->search ( $criteria, $modelClass = "ASolrDocument" );
		return $query_response;
	}
	public static function getQueryResponseCore($criteria, $model) {
		$query_response = Yii::app ()->solr_core->search ( $criteria, $modelClass = "ASolrDocument" );
		return $query_response;
	}
}
?>