/**
 * A class from the O'Reilly Book
 * "Database Programming with JDBC and Java, 2nd Edition
 * By George Reese ISBN: 1-56592-616-1.
 *
 * Adapted by Jason Grafinger
 */

package com.example.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import javax.servlet.*;

public class AuthServlet extends HttpServlet {

    private Properties connectionProperties = new Properties();
    private Driver     driver               = null;
    private String     driverName           = null;
    private String     jdbcURL              = null;
    private Random     random               = new Random();

    /**
     * Provides the servlet with the chance to get runtime configuration
     * values and initialize itself.  For a database servlet, you want
     * to grab the driver name, URL, and any connection information.
     * For this example, I assume a driver that requires a user name
     * and password.  For an example of more database independent
     * configuration, see Chapter 4.
     * @param cfg the servlet configuration information
     * @throws javax.servlet.ServletException could not load the specified
     * JDBC driver
     */

    public void init(ServletConfig cfg) throws ServletException {
        super.init(cfg);
        {
            String user, pw;
	    ServletContext ctx = getServletContext();
            driverName = ctx.getInitParameter("gb.driver");
	    System.out.println("JASON DEBUG: driverName=" + driverName);
	    System.out.flush();
            jdbcURL = ctx.getInitParameter("gb.jdbcURL");
            user = ctx.getInitParameter("gb.user");
            if( user != null ) {
                connectionProperties.put("user", user);
            }
            pw = ctx.getInitParameter("gb.pw");
            if( pw != null ) {
                connectionProperties.put("password", pw);
            }
            try {
                driver = (Driver)Class.forName(driverName).newInstance();
            }
            catch( Exception e ) {
                throw new ServletException("Unable to load driver: " +
                                           e.getMessage());
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        Locale loc = getLocale(request);
        String name, email, comment;
        Connection conn = null;
        Exception err = null;
        int id = -1;

	RequestDispatcher view;

	HttpSession session = request.getSession(true);
	//retrieve or create session

        //String tmp = request.getParameter("type");



        try {
            ResultSet result;
            Statement stmt;

            conn = DriverManager.getConnection(jdbcURL, connectionProperties);

            stmt = conn.createStatement();
            result = stmt.executeQuery("SELECT userID " +
				       "FROM a10_users " +
				       "WHERE name=\"" +
				       request.getParameter("username") +
				       "\" AND password=\"" +
				       request.getParameter("password") + "\"");

	    if(result.next())
		{
		    //There exists a user with that name/password combo
		    User user;

		    if(session.isNew()) {
						user = new User();
						user.setLogged(1);
						user.setUserID(result.getInt("userID"));

						session.setAttribute("userID", user);
			}


		    //session.setAttribute("logged-in", 1);

		    //session.setAttribute("userID",result.getInt("userID"));

		    //User is authenticated, send to the schedule form
		    view = request.getRequestDispatcher("mainMenu.html");
		    view.forward(request, response);

		    out.println("Account has been verified");
		}
	    else
		{

		    view = request.getRequestDispatcher("loginPage.html");
		    view.forward(request, response);

		    out.println("Wrong UserName/Password");
		}
	    stmt.close();
	}
	catch(Exception e)
	{

        }
        finally {
            if( conn != null ) {
                try { conn.close(); }
                catch( Exception e ) { }
            }
        }
        if( err != null ) {
            out.println("An error occurred on save: " + err.getMessage());
        }
        else {
        }
    }

    /**
     * Find the desired locale from the HTTP header.
     * @param req the servlet request from which the header is read
     * @return the locale matching the first accepted language
     */
    private Locale getLocale(HttpServletRequest req) {
        String hdr = req.getHeader("Accept-Language");
        StringTokenizer toks;

        if( hdr == null ) {
            return Locale.getDefault();
        }
        toks = new StringTokenizer(hdr, ",");
        if( toks.hasMoreTokens() ) {
            String lang = toks.nextToken();
            int ind = lang.indexOf(';');
            Locale loc;

            if( ind != -1 ) {
                lang = lang.substring(0, ind);
            }
            lang = lang.trim();
            ind = lang.indexOf("-");
            if( ind == -1 ) {
                loc = new Locale(lang, "");
            }
            else {
                loc = new Locale(lang.substring(0, ind),
                                 lang.substring(ind+1));
            }
            return loc;
        }
        return Locale.getDefault();
    }

	/**
	 *  Print the stuff that goes at the bottom of a page that can be validated
	 */

    private void printFooter(PrintWriter out, Locale loc)
    {
	    out.println("<hr />");
	    out.println("<p><a href=\"http://validator.w3.org/check?uri=referer\">");
		out.println("     <img src=\"http://www.udel.edu/CIS/images/valid-xhtml11.png\"");
		out.println("       alt=\"Valid XHTML 1.1\" width=\"88\" height=\"31\" ");
		out.println("       longdesc=\"http://validator.w3.org\" /></a>");
        out.println("   <a href=\"http://jigsaw.w3.org/css-validator/check/referer\">");
        out.println("      <img style=\"border:0;width:88px;height:31px\"");
        out.println("        src=\"http://www.udel.edu/CIS/images/vcss.png\"");
        out.println("        alt=\"Valid CSS!\" /></a>");
		out.println("</p>");
   }

}












