package eu.dnetlib.enabling.ui.server;


import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.aas.rmi.A2Service;
import eu.dnetlib.enabling.aas.rmi.AuthenticateRequest;
import eu.dnetlib.enabling.aas.rmi.AuthenticateResp;
import eu.dnetlib.enabling.aas.rmi.AuthorizeRequest;
import eu.dnetlib.enabling.aas.rmi.TypedString;
import eu.dnetlib.enabling.tools.ServiceLocator;

public class AuthenticationManagerAAS implements AuthenticationManager {

	/**
	 * Locator of A2Service.
	 */
	private ServiceLocator<A2Service> a2SLocator;
	/**
	 * Resource for which the authorization is requested.
	 */
	private String resource;
	/**
	 * Action to be performed on the resource.
	 */
	private String action;
	
	public boolean authenticate(String email, String password) {
		
		A2Service aas = a2SLocator.getService();
			
		AuthenticateRequest request = new AuthenticateRequest();

		TypedString principals = this.createTypedString("login", email);
		TypedString credentials = this.createTypedString("password", password);

		TypedString principalsArray[] = new TypedString[] {principals};
		TypedString credentialsArray[] = new TypedString[] {credentials};

		request.setPrincipals(principalsArray);
		request.setCredentials(credentialsArray);

		AuthenticateResp a2Response = aas.authenticate(request);

		if ((a2Response.getErrors() != null && a2Response.getErrors().length > 0)) {
			return false;
		}

		AuthorizeRequest req2 = new AuthorizeRequest();
		req2.setContextId(a2Response.getContextId());
		req2.setResource(createTypedString(null, resource));
		req2.setAction(createTypedString(null, action));

		return aas.authorize(req2).isAuthorized();
	}


	private TypedString createTypedString(String type, String value) {
		TypedString s = new TypedString();

		s.setText(value);
		s.setType(type);

		return s;
	}


	public ServiceLocator<A2Service> getA2SLocator() {
		return a2SLocator;
	}

	@Required
	public void setA2SLocator(ServiceLocator<A2Service> aasLocator) {
		this.a2SLocator = aasLocator;
	}


	public String getResource() {
		return resource;
	}

	@Required
	public void setResource(String resource) {
		this.resource = resource;
	}


	public String getAction() {
		return action;
	}

	@Required
	public void setAction(String action) {
		this.action = action;
	}

}
