package org.gcube.application.geoportal.model.vre;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

import org.gcube.application.geoportal.model.fault.GenericWebException;
import org.gcube.application.geoportal.utils.ISUtils;
import org.gcube.data.transfer.library.client.AuthorizationFilter;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.json.JSONException;
import org.json.JSONObject;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class SocialManager {

	Client client;
	String baseUrl;

	private SocialManager() {
		log.debug("Looking for social networking..");		
		baseUrl=ISUtils.getgCubeBaseEndpoint("Portal", "SocialNetworking");
		log.debug("Social Networking service is at "+baseUrl);

		ClientConfig config=new ClientConfig();
		config.register(AuthorizationFilter.class);

		client=ClientBuilder.newClient(config)
				.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
	}


	private JSONObject read(String path) throws JSONException, GenericWebException {
		return check(client.target(baseUrl).path(path).request().get());
	}

	private static JSONObject check(Response resp) throws JSONException, GenericWebException {
		if(resp.getStatus()<200||resp.getStatus()>=300) {
			String remoteMessage=resp.readEntity(String.class);
			Integer httpCode=resp.getStatus();
			GenericWebException e=new GenericWebException("RESP STATUS IS "+httpCode+". Message : "+remoteMessage);
			e.setRemoteMessage(remoteMessage);
			e.setResponseHTTPCode(httpCode);
			throw e;
		}else {
			String respString=resp.readEntity(String.class);
			log.debug("Response is "+respString);
			return new JSONObject(respString);
		}
	}


	public static GCubeUser getCurrentUser() {

		String id="fakeID";
		String currentVRE="fakeVRE";
		String name="NO NAME";
		try {
		SocialManager manager=new SocialManager();

		JSONObject obj=manager.read("2/people/profile");
		if(obj.getBoolean("success")) {
			JSONObject result=obj.getJSONObject("result");
			
			currentVRE=result.getString("context");
			name=result.getString("fullname");
			id=result.getString("username");
			
			
		}else throw new Exception("Service reported fail : "+obj.toString());
		}catch(Throwable t) {
			log.warn("!!!!! UNABLE TO CONTACT SOCIAL NETWORKING SERVICE ",t);
		}
		return new GCubeUser(id, name, currentVRE);

	}

}
