/**
 * 
 */
package cz.hsrs.rest.provider;

import java.sql.SQLException;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.eclipse.jetty.http.HttpStatus;

import cz.hsrs.db.model.NoItemFoundException;
import cz.hsrs.db.util.UserUtil;
import cz.hsrs.rest.beans.ExceptionBean;
import cz.hsrs.rest.beans.UserBean;
import cz.hsrs.rest.util.AuthUtil;
import cz.hsrs.rest.util.UserRestUtil;
import cz.hsrs.servlet.security.LoginUser;
import net.sf.json.JSONObject;

/**
 * @author mkepka
 *
 */
@Path("/user")
public class UserRest {
    
    /**
     * Empty constructor
     */
    public UserRest() {
    }
    
    /**
     * Method for getting user details
     * URL: /rest/user
     * @param req
     * @return
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser(@Context HttpServletRequest req) {
        try {
            LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);
            UserBean userDetails = UserRestUtil.getUser(loggedUser.getUserName());
            return Response.ok().entity(userDetails)
                    .build();
        } catch (AuthenticationException e1) {
            return Response.status(HttpStatus.UNAUTHORIZED_401)
                    .entity(new ExceptionBean(e1.getClass().getName(), "Authentication failure for request!"))
                    .build();
        } catch (SQLException e) {
            return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500)
                    .entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                    .build();
        }
    }
    
    /**
     * Method for inserting user
     * URL: /rest/user
     * @param userJSON
     * @param req
     * @return
     */
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response insertUser(JSONObject userJSON, @Context HttpServletRequest req) {
        try {
            LoginUser loggedUser = AuthUtil.getAuthenticatedLoginUser(req);
            if(loggedUser.getRightsID() == 0) {
            	if(!checkDuplicity(userJSON.getString("userName"))) {
            		UserUtil.insertUser(userJSON.getString("userName"),
                            userJSON.getString("userPass"),
                            userJSON.getString("userRealName"),
                            userJSON.getInt("groupId"),
                            userJSON.getInt("rightsId"));
            		return Response.ok()
                            .build();
            	} else {
                    return Response.status(HttpStatus.ORDINAL_409_Conflict)
                            .entity(new ExceptionBean("Exception", "User with given name cannot be created!"))
                            .build();
            	}
            
            }
            else {
                return Response.status(HttpStatus.FORBIDDEN_403)
                        .entity(new ExceptionBean("AuthenticationException", "Not enough rights!"))
                        .build();
            }
        } catch (AuthenticationException e1) {
            return Response.status(HttpStatus.UNAUTHORIZED_401)
                    .entity(new ExceptionBean(e1.getClass().getName(), "Authentication failure for request!"))
                    .build();
        } catch (SQLException e) {
            return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500)
            		.entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                    .build();
        }
    }
    
    /**
     * Function check if user with same userName already exists in DB
     * @param userName - name of user
     * @return true if userName is already used
     * 			false if userName is not used
     * @throws SQLException
     */
    private boolean checkDuplicity(String userName) throws SQLException {
		UserUtil uUtil = new UserUtil();
		try {
			uUtil.getUserId(userName);
			return true;
		} catch (NoItemFoundException e) {
			return false;
		} catch (SQLException e) {
			throw new SQLException(e);
		}
	}

	/**
     * 
     * URL: /rest/user/rights
     * @param req
     * @return
     */
    @Path("/rights")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getRights(@Context HttpServletRequest req) {
        try {
            
            AuthUtil.getAuthenticatedLoginUser(req);
            
            return Response.ok(UserRestUtil.getAllRights())
                    .build();
        } catch (AuthenticationException e) {
            return Response.status(HttpStatus.UNAUTHORIZED_401)
                    .entity(new ExceptionBean(e.getClass().getName(), "Authentication failure for request!"))
                    .build();
        } catch (SQLException e) {
            return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500)
                    .entity(new ExceptionBean(e.getClass().getName(), e.getLocalizedMessage()))
                    .build();
        }
    }
}