package com.example.beer.services;

import java.net.HttpURLConnection;

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

import com.example.beer.dao.UserDAO;
import com.example.beer.model.User;
import com.example.beer.model.WebUser;

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

	@Inject
	private UserDAO userDAO;

	@Inject
	private UserContext userContext;

	@POST
	@Path("login")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response login(WebUser user) {
		User foundUser = userDAO.validateCredentials(
				user.getUsername(), user.getPassword());
		
		if (foundUser != null) {
			userContext.setCurrentUser(foundUser);
            return Response.status(HttpURLConnection.HTTP_OK).build();
		}

        return Response.status(HttpURLConnection.HTTP_UNAUTHORIZED).build();
	}
	
	@POST
	@Path("logout")
	public Response logout() {
		userContext.setCurrentUser(null);
        return Response.status(HttpURLConnection.HTTP_OK).build();
	}
	
	@POST
	@Path("register")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response registerNewUser(User user) {
		User currentUser = userContext.getCurrentUser();
		
		if (currentUser.isAdmin()) {
			if (userDAO.getUserByName(user.getName()) == null) {
                userDAO.addUser(user);
                return Response.status(HttpURLConnection.HTTP_OK).build();
			} else {
                return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
			}
		}
		
        return Response.status(HttpURLConnection.HTTP_FORBIDDEN).build();
	}

}

@@ -668,13 +668,8 @@
 als(
-%0A%09%09%09%09
 user
@@ -683,17 +683,21 @@
 rname(),
- 
+%0A%09%09%09%09
 user.get
@@ -709,18 +709,16 @@
 ord());%0A
-%09%09
 %0A%09%09if (f
@@ -779,28 +779,19 @@
 dUser);%0A
-            
+%09%09%09
 return R
@@ -846,24 +846,18 @@
 );%0A%09%09%7D%0A%0A
-        
+%09%09
 return R
@@ -912,33 +912,32 @@
 ED).build();%0A%09%7D%0A
-%09
 %0A%09@POST%0A%09@Path(%22
@@ -1009,24 +1009,18 @@
 (null);%0A
-        
+%09%09
 return R
@@ -1073,17 +1073,16 @@
 d();%0A%09%7D%0A
-%09
 %0A%09@POST%0A
@@ -1242,112 +1242,128 @@
 ;%0A%09%09
-%0A%09%09if (currentUser.isAdmin()) %7B%0A%09%09%09if (userDAO.getUserByName(user.getName()) == null) %7B%0A                
+User foundUser = userDAO.getUserByName(user.getName());%0A%0A%09%09if (currentUser.isAdmin()) %7B%0A%09%09%09if (foundUser == null) %7B%0A%09%09%09%09
 user
@@ -1381,32 +1381,20 @@
 (user);%0A
-                
+%09%09%09%09
 return R
@@ -1460,24 +1460,12 @@
 e %7B%0A
-                
+%09%09%09%09
 retu
@@ -1538,19 +1538,11 @@
 %09%09%7D%0A
+%0A
 %09%09
-%0A        
 retu

Refactor UserManager.register method