package uk.ac.ebi.biosamples.service;

import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import uk.ac.ebi.biosamples.model.ExternalReference;

@Service
public class ExternalReferenceService {
	
	public String getNickname(ExternalReference externalReference) {
		//TODO make this more configurable
		if (externalReference.getUrl().contains("www.ebi.ac.uk/ena")) {
			return "ENA";
		} else if (externalReference.getUrl().contains("www.ebi.ac.uk/arrayexpress")) {
			return "ArrayExpress";
		} else if (externalReference.getUrl().contains("hpscreg.eu/")) {
			return "hPSCreg";
		} else {
			return "other";
		}
	}

	public Optional<String> getDataId(ExternalReference externalReference) {
		
		String nickname = getNickname(externalReference);		
		if ("ENA".equals(nickname)) {
			UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(externalReference.getUrl()).build();
			String lastPathSegment = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size()-1);
			return Optional.of(lastPathSegment);
		}
		if ("ArrayExpress".equals(nickname)) {
			UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(externalReference.getUrl()).build();
			String lastPathSegment = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size()-1);
			return Optional.of(lastPathSegment);	
		}
		if ("hPSCreg".equals(nickname)) {
			UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(externalReference.getUrl()).build();
			String lastPathSegment = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size()-1);
			return Optional.of(lastPathSegment);
		}
        return Optional.empty();
	}
}

@@ -704,16 +704,120 @@
 SCreg%22;%0A
+%09%09%7D else if (externalReference.getUrl().contains(%22ncbi.nlm.nih.gov/projects/gap%22)) %7B%0A%09%09%09return %22dbGaP%22;%0A
 %09%09%7D else
@@ -819,16 +819,16 @@
  else %7B%0A
-
 %09%09%09retur
@@ -1258,27 +1258,30 @@
 egment);%0A%09%09%7D
-%0A%09%09
+ else 
 if (%22ArrayEx
@@ -1561,19 +1561,22 @@
 t);%09%0A%09%09%7D
-%0A%09%09
+ else 
 if (%22hPS
@@ -1803,32 +1803,32 @@
 ts().size()-1);%0A
-
 %09%09%09return Option
@@ -1851,16 +1851,265 @@
 gment);%0A
+%09%09%7D else if (%22dbGaP%22.equals(nickname)) %7B%0A%09%09%09UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(externalReference.getUrl()).build();%0A%09%09%09String studyId = uriComponents.getQueryParams().getFirst(%22study_id%22);%0A%09%09%09return Optional.of(studyId);%0A
 %09%09%7D%0A    

add dbgap external reference handling