import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;
import java.sql.*;

public class LoginServlet2 extends HttpServlet
{
	public void init(ServletConfig config) throws ServletException
	{
		try
		{
			// open the database connections and prepare the statment
			WebSecurityManager.init("Example");
		}
		catch ( WebSecurityManagerException sE)
		{
			throw new ServletException( sE.getMessage() );
		}
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		// check to see if a session has already been created for this user
		//		don't create a new session yet.
		HttpSession session = request.getSession( false);

		String requestedPage = request.getParameter(Constants.REQUEST);

		if ( session == null)
		{

			// retrieve the username and password from the request
			String sUserName = request.getParameter( Constants.USERNAME);
			String sPassword = request.getParameter( Constants.PASSWORD);

			// AUTHENTICATE the user
			User user = null;
			Feature feature = null;

			try
			{

				user = WebSecurityManager.retrieveUser( sUserName,  sPassword, "Example");

				feature = WebSecurityManager.getFeature(requestedPage);
			}
			catch (WebSecurityManagerException smE)
			{
				smE.printStackTrace();
			}

			if ( user != null && WebSecurityManager.isUserAuthenticated( user, feature))
			{
				// create a session
				session = request.getSession( true);

				// store the boolean value to the session
				session.putValue( Constants.USER, user);

				// redirect to the entered page
				response.sendRedirect( feature.getFeaturePath() );

			}
			else
			{
				// redirect to the login servlet (passing parameter)
				response.sendRedirect( Constants.LOGIN + requestedPage);
			}
		}
	}

	private static boolean authenticateUser(String sUserName, String sPassword )
	{
		return JDBCHelper.authenticateUser(sUserName, sPassword);
	}
}
