package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/** Servlet class that performs the request 
  * to get users times
  * 
  * @author Yana Novikova, Tara Strobel
  * @version A10
  */
public class FreeTimeResult extends HttpServlet {

    /** Database url */
    private String url;
    /** User name */
    private String user;
    /** Password */
    private String pw;

    /** Provides the servlet with the chance to get runtime configuration
     * values and initialize itself. It gets driver URL, username and password
     * from web.xml file
     *
     * @param cfg Servlet Configuration
     */
    public void init(ServletConfig cfg) throws ServletException {
	super.init(cfg);
	{
	    ServletContext ctx = getServletContext();

	    //get all information
	    url = ctx.getInitParameter("url");
	    user = ctx.getInitParameter("user");
	    pw = ctx.getInitParameter("passwd");
	}
    }

    /** Performs HTTP POST request 
     * and returns common free times to jsp page
     * 
     * @param request Http Servlet Request
     * @param response Http Servlet Response
     */
    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
		throws IOException, ServletException {

            
	String[] params =  request.getParameterValues("name");
        int s_h = Integer.parseInt(request.getParameter("start_h"));
        int s_m = Integer.parseInt(request.getParameter("start_m"));
        int e_h = Integer.parseInt(request.getParameter("end_h"));
        int e_m = Integer.parseInt(request.getParameter("end_m"));
        String users = request.getParameter("user");
	String result;
	String unames = "";
	Scheduler sch = new Scheduler();
	sch.setSqlConnVars(url, user, pw);

	if(params == null) {
	   result = "<script type='text/javascript'> " + 
		    "alert('NO USERS SELECTED!: Click Find Common Free Times to try again!')" +
	            "</script>";
	}
        else{
	   sch.setTimeConstraint_StartTime(s_h,s_m);
	   sch.setTimeConstraint_EndTime(e_h,e_m);
	   result = sch.getUserSchedule(params);
	   unames += params[0];
	   for(int i=1; i<params.length; i++) {
		unames += ", " + params[i];
	   }	
	}

	request.setAttribute("styles", result);
	request.setAttribute("unames", unames);
        request.setAttribute("user", users);
	RequestDispatcher view = request.getRequestDispatcher("getschedule_result.jsp");
	view.forward(request, response);
    }
}
