<?php

namespace common\models;

use Yii;
use DOMDocument;
use common\models\SOLRQueryManager;

/*
 * This ExploreManager handles request to external services (GBIF, EOL ...)
 */
class ExploreManager {
	public static function getGBIFRecords($keyList) {
		$GBIFs = [ ];
		foreach ( array_unique ( $keyList ) as $key ) {
			if ($key != "") {
				$url = "http://www.gbif.org/occurrence/search?TAXON_KEY=" . $key . "&BASIS_OF_RECORD=PRESERVED_SPECIMEN&BASIS_OF_RECORD=LIVING_SPECIMEN";
				$count = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=LIVING_SPECIMEN";
				$content1 = file_get_contents ( $count );
				$count2 = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=PRESERVED_SPECIMEN";
				$content2 = file_get_contents ( $count2 );
				if ($content1 > 0 || $content2 > 0)
					$GBIFs [] = [ 
							$content2 + $content1,
							$url,
							' specimen(s)' 
					];
				
				$url = "http://www.gbif.org/occurrence/search?TAXON_KEY=" . $key . "&BASIS_OF_RECORD=FOSSIL_SPECIMEN";
				$count = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=FOSSIL_SPECIMEN";
				$content = file_get_contents ( $count );
				if ($content > 0)
					$GBIFs [] = [ 
							$content,
							$url,
							' fossil(s)' 
					];
			}
		}
		return $GBIFs;
	}
	public static function getGBIFRecord($key) {
		$GBIFs = [ ];
		if ($key != "") {
			$url = "http://www.gbif.org/occurrence/search?TAXON_KEY=" . $key . "&BASIS_OF_RECORD=PRESERVED_SPECIMEN&BASIS_OF_RECORD=LIVING_SPECIMEN";
			$count = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=LIVING_SPECIMEN";
			$content1 = file_get_contents ( $count );
			$count2 = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=PRESERVED_SPECIMEN";
			$content2 = file_get_contents ( $count2 );
			if ($content1 > 0 || $content2 > 0)
				$GBIFs [] = [ 
						$content2 + $content1,
						$url,
						' specimen(s)' 
				];
			
			$url = "http://www.gbif.org/occurrence/search?TAXON_KEY=" . $key . "&BASIS_OF_RECORD=FOSSIL_SPECIMEN";
			$count = "http://api.gbif.org/v1/occurrence/count?taxonKey=" . $key . "&basisOfRecord=FOSSIL_SPECIMEN";
			$content = file_get_contents ( $count );
			if ($content > 0)
				$GBIFs [] = [ 
						$content,
						$url,
						' fossil(s)' 
				];
		}
		if (! empty ( $GBIFs ))
			foreach ( $GBIFs as $GBIF )
				echo '<a href="' . $GBIF [1] . '" target="_blank" >' . $GBIF [0] . $GBIF [2] . ' </a><br/>';
	}
	public static function getNCBIRecord($key) {
		$NCBI = [ ];
		
		if ($key != "") {
			 //echo "look for ".$key."<br/>";
			$outurl = "https://www.ncbi.nlm.nih.gov/nuccore/?term=txid" . $key . "[Organism:exp]";
			$urlNT = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nuccore&term=txid" . $key . "[Organism:exp]";
			$xml = new DOMDocument ( '1.0', 'UTF-8' );
			$xml->load ( $urlNT );
			$eSearchResult = $xml->getElementsByTagName ( 'eSearchResult' );
			$element = $eSearchResult->item ( 0 );
			$elts = $element->childNodes;
			foreach ( $elts as $elt ) {
				$nom = $elt->nodeName;
				if ($nom == "Count") {
					$cnt = $elt->nodeValue;
					
					break;
				}
			}
			if (isset ( $cnt ) && $cnt > 0)
			{ $NCBI = [ 
						$cnt . " Nucleotide record(s)",
						$outurl 
				];
			echo '<a href="' . $NCBI [1] . '" target="_blank" >' . $NCBI [0] . ' </a><br/>';
			}
		}

		
	}
	public static function getBOLDRecord($name) {
// 		echo "getBOLD for " . $name;
		$bold = "http://www.boldsystems.org/index.php/API_Public/specimen?format=xml&taxon=" . str_replace ( "_", "+", $name );
// 		echo $bold;
		$content=file_get_contents($bold);
// 		Yii::info($content);
		if($content != "") {
		$cnt = 0;
		try {
			$doc=DOMDocument::loadXML($content);
			if($doc){
				$records = $doc->getElementsByTagName ( 'record' );
				$cnt=$records->length;
			} 
		} catch ( Exception $e ) {
			echo $e;
		} 
		
		echo $cnt; }
	}
	public static function getGGBNRecords($canonicalName, $tripleidstoreid) {
		$GGBNs = [ ];
		
		if (! empty ( $canonicalName )) {
			$config = SOLRQueryManager::getConfigDetails ();
			
			$sampletypes = [ 
					"tissue",
					"DNA",
					"unknown" 
			];
			if($sampletypes != "") {
			foreach ( $sampletypes as $sampletype ) {
				$query = SOLRQueryManager::createSearchQuery ( $config );
				
				$value = str_replace ( " ", "\ ", $canonicalName );
				$value = str_replace ( "(", "\(", $value );
				$value = str_replace ( ")", "\)", $value );
				$value = str_replace ( ":", "\:", $value );
				$filters = "fullScientificName_nc:" . $value . " AND NOT tripleidstoreid:" . $tripleidstoreid . " AND sampletype:" . $sampletype;
				
				$query->setQuery ( "*:*" );
				$query->setStart ( 0 )->setRows ( Yii::$app->params ['listPerPage'] );
				
				$fq = "{!join from=lowestTripleIDs to=tripleidstoreid fromIndex=" . Yii::$app->params ['solrsearchname'] . "}" . $filters;
				$query->createFilterQuery ( 'myfilter' )->setQuery ( $fq );
				
				$query->setFields ( [ 
						"[]" 
				] );
				
				try {
					$raw_response = SOLRQueryManager::$client->select ( $query );
					$count = $raw_response->getNumFound ();
				} catch ( Solarium\Exception\UnexpectedValueException $e ) {
					$raw_response = SOLRQueryManager::$client->select ( $query );
					$count = $raw_response->getNumFound ();
				}
				
				if ($count > 0) {
					$outurl = "/" . Yii::$app->params ['siteName'] . "/search?fullScientificName=" . $canonicalName . "&sampletype=" . $sampletype;
					
					$GGBNs [] = [ 
							$count . " record(s) with " . $sampletype . "",
							$outurl
						];
		}
		} }
		}
		return $GGBNs;
		
	}
	
	public static function getCommonName($canonicalName) {
		$prefLabel = "";
		if ($canonicalName != "") {
			// echo "look for ".$canonicalName."<br/>";
			$outurl = 'http://openup.nhm-wien.ac.at/commonNames/?query={"type":"/name/common","query":"'.$canonicalName.'"}&format=edmSkos';
			$xml = new DOMDocument ( '1.0', 'UTF-8' );
			$xml->load ( $outurl );
			$Concepts = $xml->getElementsByTagName ( 'Concept' );
			foreach ($Concepts as $Concept) { 
				$Languages = $Concept->getElementsByTagName ('note');
					foreach ($Languages as $Language)
						{  $Note = $Language->nodeValue;
						if($Note == "Language: English" or $Note == "Language: en") 
					{ $prefLabel = $Concept->getElementsByTagName ( 'prefLabel')->item (0)->nodeValue; }
					
					}
			 }
		}
		if($prefLabel == "") { $prefLabel = "No common name found"; } 
		else { $prefLabel = $prefLabel; }
		{ return $prefLabel; }

	}
	
	
	
}