package com.example.web;

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

/** 
 * This class is responsible for adding times to the users' schedule within
 * the MySQL database.  It is called from the Change Schedule page.
 * 
 * @author Tara Strobel
 * @version CISC474: A10
 *
 */
public class DeleteTime 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
     */
    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");
	}
    }

    /**
     * Stores the new time from the user in the database and then calls the
     * response form to print a list of user times.
     *
     * @param request An HttpServletRequest from the form that called this function.
     * @param response An HttpSerletResponse to dispatch the results to the form.
     * @throws IOException
     * @throws ServletException
     */ 
    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
		throws IOException, ServletException {

            
        String[] param = request.getParameterValues("time");
        String users = request.getParameter("user");
	String result;
	TimeUnit tu = new TimeUnit();
	String[] uname = {user};

	Scheduler sch = new Scheduler();
	sch.setSqlConnVars(url, user, pw);

	sch.setTimeConstraint_StartTime(0,0);
	sch.setTimeConstraint_EndTime(23,59);

	for(int i=0; i<param.length; i++) {	
		sch.deleteBusyTime(param[i], users);
	}

	result = sch.getUserSchedule(uname);

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