package uk.ac.ebi.biosamples.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsunsoft.http.HttpRequest;
import com.jsunsoft.http.ResponseDeserializer;
import com.jsunsoft.http.ResponseHandler;
import org.springframework.stereotype.Service;
import uk.ac.ebi.biosamples.model.ENAHtsgetTicket;
import com.jsunsoft.http.HttpRequestBuilder;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Service
public class ENAHtsgetService {

    private final String host = "service_host/ga4gh/sample";

    public ENAHtsgetTicket getTicket(String accession, String format){
        HttpRequest<String> request = HttpRequestBuilder.
                createGet(String.format("%s?accession=%s&format=%s",host,accession,format), String.class)
                .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
                .build();
        ResponseHandler<String> responseHandler = request.execute();
        String jsonResponse = responseHandler.get();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = null;
        try {
            node = mapper.readTree(jsonResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        node = node.get("htsget");

        ENAHtsgetTicket ticket = new ENAHtsgetTicket();
        ticket.setAccession(accession);
        ticket.setFormat(format);

        String md5 = node.get("md5").asText();
        ticket.setMd5Hash(md5);

        JsonNode urls = node.get("urls");
        Iterator<JsonNode> urlsIterator = urls.elements();
        while(urlsIterator.hasNext()){
            JsonNode currentUrl = urlsIterator.next();
            ticket.addFtpLink(currentUrl.get("url").asText());
        }
        return ticket;


    }



}

@@ -461,31 +461,8 @@
 tor;
-%0Aimport java.util.List;
 %0A%0A@S
@@ -538,35 +538,71 @@
  = %22
-service_host/ga4gh/sample%22;
+http://localhost:8080/ga4gh/sample%22; //TODO change host to real
 %0A%0A  
@@ -668,17 +668,19 @@
  format)
-%7B
+ %7B%0A
 %0A       
@@ -777,22 +777,12 @@
 (%22%25s
-?accession=%25s&
+/%25s?
 form
@@ -792,13 +792,15 @@
 %25s%22,
+ 
 host,
+ 
 acce
@@ -805,16 +805,17 @@
 cession,
+ 
 format),
@@ -1483,16 +1483,20 @@
 get(%22md5
+Hash
 %22).asTex
@@ -1647,16 +1647,17 @@
    while
+ 
 (urlsIte
@@ -1672,16 +1672,17 @@
 sNext())
+ 
 %7B%0A      
@@ -1836,11 +1836,10 @@
     %7D%0A%0A%0A
-%0A
 %7D%0A

fix issue with md5 hash