package com.studentsnews.services;

import java.net.HttpURLConnection;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.studentsnews.dao.UserDAO;
import com.studentsnews.models.User;

@Stateless
@Path("user")
public class UserManager {

	private static final Response RESPONSE_OK = Response.ok().build();

	@Inject
	private UserDAO userDAO;

	@Inject
	private UserContext context;

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<User> getAllUsers() {
		return userDAO.getAllUsers();
	}

	@Path("register")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response registerUser(User newUser) {
		if (newUser.getFirstName().length() > 0 && newUser.getFirstName().length() < 20
				&& newUser.getLastName().length() > 0 && newUser.getLastName().length() < 20) {
			if (newUser.getPassword().length() >= 8) {
				if (userDAO.addUser(newUser)) {
					return RESPONSE_OK;
				}

			}
		}
		return Response.status(401).build();
	}

	@Path("login")
	@POST
	@Consumes("application/json")
	public Response loginUser(User user) {
		boolean isUserValid = userDAO.validateUserCredentials(user.getUserName(), user.getPassword());
		if (!isUserValid) {
			return Response.status(HttpURLConnection.HTTP_UNAUTHORIZED).build();
		}

		User curUser = userDAO.findUserByUserName(user.getUserName());
		System.out.println(curUser);
		context.setCurrentUser(curUser);
		return RESPONSE_OK;
	}

}

@@ -1125,17 +1125,16 @@
 ;%0A%09%09%09%09%7D%0A
-%0A
 %09%09%09%7D%0A%09%09%7D
@@ -1622,12 +1622,402 @@
 E_OK;%0A%09%7D
+%0A%09%0A%09@Path(%22current%22)%0A%09@GET%0A%09@Produces(MediaType.APPLICATION_JSON)%0A%09public String getUser() %7B%0A%09%09if (context.getCurrentUser() == null) %7B%0A%09%09%09System.out.println(context.getCurrentUser().getFirstName());%0A%09%09%09return %22null%22;%0A%09%09%7D%0A%09%09return context.getCurrentUser().toString();%0A%09%7D%0A%09%0A%09@Path(%22logout%22)%0A%09@GET%0A%09@Consumes(MediaType.TEXT_PLAIN)%0A%09public void logoutUser() %7B%0A%09%09context.setCurrentUser(null);%0A%09%7D
 %0A%0A%7D%0A

add user logout/current