/************************************************
A SchedulCreator class reads information from the form
and sends it to the model class.  the model class takes the 
information and computes the answer and sends it to a simple JSP
@author Anthony Furst

*************************************************/
package com.example.web;

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

public class ScheduleCreator extends HttpServlet {
/*******************************************
gets information from form and sends it to the model class.
@throws IOException
@throws ServletException
@see HttpServlet
@param request page where gets info from
@param response page where it is sent to
********************************************/
    public void doPost(HttpServletRequest request,
		       HttpServletResponse response) 
	throws IOException, ServletException {

	String constraints = (String)request.getParameter("constraints");
	String tempString = "";
	String busyTimes = "";
	String freeTimes = "";
        String errorMessage = "";

	//Concat all user times together into one string
	//Takes into account NULL strings in which the user has not entered anything
	for (int i = 0; i < 4; i++) {
	    tempString = (String)request.getParameter("user" + (i+1));
	    if (busyTimes.equals("") && tempString.length() > 0) 
		busyTimes = tempString;
	    else if (tempString.length() > 0)
		busyTimes += ", " + tempString;
	}

	Schedule sched = new Schedule();

	try {
	    sched.setFreeTimeConstraints(constraints);
	}
	catch (FreeTimesAlreadySetException e) {
	    errorMessage = e.getMessage();
	    forwardRequest(errorMessage, freeTimes, request, response);
	    return;
	}

	try {
	    if (!busyTimes.equals("")) 
		sched.setBusyTimes(busyTimes);
	}
	catch (FreeTimesNotSetException e) {
	    errorMessage = e.getMessage();
	    forwardRequest(errorMessage, freeTimes, request, response);
	    return;
	}
	
	freeTimes = sched.getFreeTimes();
	forwardRequest(errorMessage, freeTimes, request, response);
    }
/********************************************
sets attrisends the information to the JSP
@throws IOexception
@throws ServletException
@param errorMessage if there is an error it displays it
@param freeTimes the freetimes are sent to the jsp
@param request page where info is from
@param sends it to the result.jsp
*********************************************/
    private void forwardRequest(String errorMessage, String freeTimes, 
				HttpServletRequest request, HttpServletResponse response) 
	throws IOException, ServletException {
	request.setAttribute("free times", freeTimes);
	request.setAttribute("errorMessage", errorMessage);
	    
	RequestDispatcher view = 
	    request.getRequestDispatcher("result.jsp");
	
	view.forward(request, response);
    }
}
