package com.microstar.tap3.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RestUtil
{

	public static <T> T fromJSON(final ObjectMapper mapper, final TypeReference<T> type, final String jsonPacket) throws JsonParseException, JsonMappingException, IOException 
	{
		T data = null;

		data = mapper.readValue(jsonPacket, type);
		return data;
	}
	
	public static void sleep(int seconds)
	{
		try
		{
			Thread.sleep(seconds*1000);
		}
		catch ( Exception ex )
		{
			System.err.println("Error caught in RestUtil.sleep:");
			ex.printStackTrace(System.err);
		}
	}
	
	public static String pingService(String serviceURI, int numAdditionalInstancesToPing, Logger LOG)
	{
		
		try
		{
			Client client = ClientBuilder.newClient();
			String baseUrl = serviceURI + "?numAdditionalInstancesToPing=" + numAdditionalInstancesToPing;
			WebTarget target = client.target(baseUrl);
			Builder builder = target.request().accept(MediaType.APPLICATION_JSON_TYPE);
			LOG.info("PingService::Calling ping " + baseUrl);
			Response response = builder.head();
			if ( response.getStatus() != Response.Status.OK.getStatusCode() )
			{
				LOG.info("PING ERROR: Calling ping from ping failed: " + response.getStatus());
			}
			LOG.info("PingService::Done calling " + baseUrl);
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}

		return null;
	}
	
	public static Response response(Status status, String message)
	{
		return Response
				.status(status)
				.header("Access-Control-Allow-Origin", "*")
				.entity(message)
				.build();
	}
	public static <T> Response response(Status status, T entity, String baseUri) 
	{
		return Response
				.status(status)
				.entity(entity)
				.header("Access-Control-Allow-Headers", "Content-Type,Accept")
				.header("Access-Control-Allow-Origin", "*")
				.location(RestUtil.makeURI(baseUri))
				.build();
	}
	
	public static String errorMsg(String message, Object detail)
	{
		String ret = "{\"error\": \"" + message + "\"";
		if ( detail != null )
			ret += ", \"detail\": \"" + detail + "\"";
		
		ret += "}";
		
		return ret;
	}

	public static URI makeURI(String uri)
	{
		try
		{
			return new URI(null, null, "/v3" + uri, null);
		}
		catch ( URISyntaxException use )
		{
			System.out.println("Caught exception creating URI with: " + uri);
			use.printStackTrace();
			return null;
		}
	}
}
