package com.armundia.app.login;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import com.armundia.core.users.entity.SeUsers;
import com.armundia.v2.shared.exception.ArmundiaException;

@Path("authentication")
@Produces("application/json")
public class LoginRest {

	@Context
	private HttpServletRequest request;

	@Inject
	private LoginManager loginManager;
	
	@POST()
	@Path("login")
	public Response login(
			@FormParam("userid") String userid,
			@FormParam("password") String password,
			@FormParam("clientVersion") String clientVersion
			) throws ArmundiaException {

		String ipAddress = request.getRemoteAddr();
		String userAgent = request.getHeader("User-Agent");

		SeUsers user = loginManager.login(userid, password, ipAddress, userAgent, clientVersion);
		
		String jsessionid = request.getSession(false).getId();

		DatiUtentePojo dup = loginManager.postLogin(user, jsessionid);
		
		return Response.ok(dup).build();
	}
	
	@POST()
	@Path("logout")
	public Response logoutPOST(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		loginManager.logout(request, response);
		
		return Response.ok(new DatiUtentePojo()).build();
	}
}
