package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
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.*;

/**
   SchedulerAdd acts as the controller for our Scheduler web-app. It takes the
   values entered in our web form, creates Events corresponding to those
   values, adds them to a schedule, and then displays a schedule of the free
   times.
   @author Peter Park/ added database support by Ryan Whited
   @version 2006-4-19
*/

public class SchedulerAdd extends HttpServlet
{
  /**
     Acts as the controller for our Scheduler web-app. Takes the data entered
     in our web form, uses the model classes to build a schedule, finds the
     free times associated with it, and creates a web page with the results.
     @param request the servlet request
     @param response the servlet response
  */

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



  public void init(ServletConfig cfg) throws ServletException {
          super.init(cfg);
          {
              String user, pw;
  	    ServletContext ctx = getServletContext();
              driverName = ctx.getInitParameter("gb.driver");

              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 addToDB(Event evt,int ID) {

	  //Connection for the database
	  Connection conn = null;

	  int userID = ID;
	  int day = evt.getID();
	  int startTime = evt.getStartTime();
	  int endTime = evt.getEndTime();

	  final String sql_com = "insert ignore into a10_events (userID,day,start,end) values ("
	  							+ userID + "," + day + "," + startTime + "," + endTime + ");";


	  try {
	              Statement stmt;

	              conn = DriverManager.getConnection(jdbcURL, connectionProperties);

	              stmt = conn.createStatement();
	              stmt.executeUpdate(sql_com);

	  }
	  catch(Exception e)
	  {}
	  finally {if( conn != null ) {
		  try { conn.close(); }
		  catch( Exception e ) { }
		  }
	  }

 }


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



      System.out.println("zzzz starting the POST for SchedulerAdd servlet");

    HttpSession session = request.getSession(true); //retrieve a session
    Schedule a = null;                //create new Schedule

    //gets the users ID -- NOT WORKING -- 7 is for testing
    User user = new User();

    //user = ((User)session.getAttribute("UserID"));

    int userID = user.getUserID();//((int)session.getAttribute("UserID"));


    // Linked list to hold the events already inputted by the user
    LinkedList<Event> EventsQ = new LinkedList<Event>();

    // If Session already exists, then grab schedule from session
    if(!(session.isNew()) && session.getAttribute("sch")!= null)
    {
      a = (Schedule) session.getAttribute("sch");

      if(session.getAttribute("evtq") != null)
	  EventsQ = (LinkedList<Event>) session.getAttribute("evtq");

      else
	  EventsQ = new LinkedList<Event>();
    }
    else
	{
	    a = new Schedule();
	    EventsQ = new LinkedList<Event>();
	}

    // Check form's hidden formflag tag, user set global constraint
    if(request.getParameter("firstform")!=null
       && request.getParameter("firstform").equals("88"))
    {
      Event mon = new Event(1, 0, 2400);
      Event tues = new Event(2, 0, 2400);
      Event wed = new Event(3, 0, 2400);
      Event thurs = new Event(4, 0, 2400);
      Event fri = new Event(5, 0, 2400);
      Event sat = new Event(6, 0, 2400);
      Event sun = new Event(0, 0, 2400);
      if(request.getParameter("mon")!=null
         && request.getParameter("mon").equals("1"))
      {
		addToDB(mon,userID);
        a.addEvent(mon);
        EventsQ.add(mon);
      }
      if(request.getParameter("tues")!=null
         && request.getParameter("tues").equals("1"))
      {
		addToDB(tues,userID);
        a.addEvent(tues);
        EventsQ.add(tues);
      }
      if(request.getParameter("wed")!=null
         && request.getParameter("wed").equals("1"))
      {
		addToDB(wed,userID);
        a.addEvent(wed);
        EventsQ.add(wed);
      }
      if(request.getParameter("thurs")!=null
         && request.getParameter("thurs").equals("1"))
      {
		addToDB(thurs,userID);
        a.addEvent(thurs);
        EventsQ.add(thurs);
      }
      if(request.getParameter("fri")!=null
         && request.getParameter("fri").equals("1"))
      {
		addToDB(fri,userID);
        a.addEvent(fri);
        EventsQ.add(fri);
      }
      if(request.getParameter("sat")!=null
         && request.getParameter("sat").equals("1"))
      {
		addToDB(sat,userID);
        a.addEvent(sat);
        EventsQ.add(sat);
      }
      if(request.getParameter("sun")!=null
         && request.getParameter("sun").equals("1"))
      {
		addToDB(sun,userID);
        a.addEvent(sun);
        EventsQ.add(sun);
      }
      session.setAttribute("sch", a);
      session.setAttribute("evtq", EventsQ);
      request.setAttribute("eventqueue", EventsQ);
      RequestDispatcher view = request.getRequestDispatcher("form.jsp");

      // Forward user to form.jsp
      view.forward(request, response);
    }
    else if(request.getParameter("thirdform")!=null && request.getParameter("thirdform").equals("99"))
    {
      String shour = request.getParameter("shour1");     // Find start hour
      String sminute = request.getParameter("sminute1"); // Find start minute
      String AMPM = request.getParameter("ampm11");      // Find AM or PM
      if(AMPM.compareTo("PM")==0 && !(shour.equals("12"))) // If it's PM, then convert to military time
      {
	Integer hour1 = Integer.parseInt(shour)+12;
	shour=hour1.toString();
      }
      else if(AMPM.compareTo("AM")==0 && shour.equals("12"))
      {
      	shour="00";
      }

      // Combine hour and minute to make one four digit time
      String start=shour+sminute;
      int starttime = Integer.parseInt(start); // Change to an integer

      String ehour = request.getParameter("ehour1");     // Find end hour
      String eminute = request.getParameter("eminute1"); // Find end minute
      String AMPM2 = request.getParameter("ampm1");      // Find AM or PM

      if(AMPM2.compareTo("PM")==0 && !(ehour.equals("12"))) // If it's PM, then convert to military time
      {
        Integer hour1 = Integer.parseInt(ehour) + 12;
	ehour = hour1.toString();
      }
      else if(AMPM2.compareTo("AM")==0 && ehour.equals("12"))
      {
      	ehour="00";
      }

      // Combine hour and minute and convert to integer
      String end=ehour+eminute;
      int endtime = Integer.parseInt(end);

        a.addGlobalConstraint(starttime, endtime);
	for(int i=0;i<7;i++)
	        {
		Event e1 = new Event(i, starttime, endtime);
		EventsQ.add(e1);
		addToDB(e1,userID);
		}

        session.setAttribute("evtq", EventsQ);
        request.setAttribute("eventqueue", EventsQ);
        session.setAttribute("sch", a);
        RequestDispatcher view = request.getRequestDispatcher("form.jsp");
        view.forward(request, response);
    }
    // Check form's hidden formflag tag, User clicked "End Session"
    else if(request.getParameter("formflag").equals("2"))
    {
      session.invalidate(); // Kill the session, user wants to start over
      RequestDispatcher view = request.getRequestDispatcher("form.jsp");
      view.forward(request, response); // Forward user to form.jsp
    }
    // User clicked "Submit" button
    else if(request.getParameter("formflag").equals("0"))
    {
	System.out.println("zzzz test form flag = 0");
	System.out.flush();

      a.formatFreeTimes(); //Format the free times
      String[] answer = a.getFormatedTime();
      ArrayList al = new ArrayList(7);
      for(int i = 0; i < 7; i++){
	  al.add(i,answer[i]);}

      request.setAttribute("freetimes", al);
      session.invalidate(); // User finished making Schedule so kill session
      RequestDispatcher view = request.getRequestDispatcher("result.jsp");
      view.forward(request, response); //Forward user to View, result.jsp
    }

    // User Clicked "Add" button
    else if(request.getParameter("formflag").equals("1"))
    {
      // Find which day user entered
      int evt_day = Integer.parseInt(request.getParameter("day1"));

      String shour = request.getParameter("shour1");     // Find start hour
      String sminute = request.getParameter("sminute1"); // Find start minute
      String AMPM = request.getParameter("ampm11");      // Find AM or PM
      if(AMPM.compareTo("PM")==0 && !(shour.equals("12"))) // If it's PM, then convert to military time
      {
	Integer hour1 = Integer.parseInt(shour)+12;
	shour=hour1.toString();
      }
      else if(AMPM.compareTo("AM")==0 && shour.equals("12"))
      {
      	shour="00";
      }

      // Combine hour and minute to make one four digit time
      String start=shour+sminute;
      int starttime = Integer.parseInt(start); // Change to an integer

      String ehour = request.getParameter("ehour1");     // Find end hour
      String eminute = request.getParameter("eminute1"); // Find end minute
      String AMPM2 = request.getParameter("ampm1");      // Find AM or PM

      if(AMPM2.compareTo("PM")==0 && !(ehour.equals("12"))) // If it's PM, then convert to military time
      {
        Integer hour1 = Integer.parseInt(ehour) + 12;
	ehour = hour1.toString();
      }
      else if(AMPM2.compareTo("AM")==0 && ehour.equals("12"))
      {
      	ehour="00";
      }

      // Combine hour and minute and convert to integer
      String end=ehour+eminute;
      int endtime = Integer.parseInt(end);

      // Create a new event with day, start time, and end time
      Event e1;
      e1 = new Event(evt_day, starttime, endtime);

      // Add event to Schedule object a
      a.addEvent(e1);	                          // Add event to Schedule

      // Add event to DataBase
      addToDB(e1,userID);

      // Save the schedule as a session attribute to be used later
      session.setAttribute("sch", a);

      // Add event to the linked list
      EventsQ.add(e1);
      session.setAttribute("evtq", EventsQ);
      request.setAttribute("eventqueue", EventsQ);
      RequestDispatcher view = request.getRequestDispatcher("form.jsp");

      // Forward user to form.jsp
      view.forward(request, response);
    }
  }
}
