import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/*
    This servlet is used only to add a movie to the Shopping
    basket.
*/

public class AddMovieServlet extends HttpServlet {

  // Method Name: init()
  // Purpose: This is the default init() method.
  public void init(ServletConfig config)
    throws ServletException {

    super.init(config);
  }

  // Method Name: addToBasket()
  // Purpose : This mathod takes the Movie object passed
  // to it and adds it to the Shopping Basket Vector
  // that is stored in the HttpSession Object
  private void addToBasket(Movie movie,
    HttpServletRequest request) {

    // Get/Create the HttpSession
    HttpSession session = request.getSession(true);

    if ( session != null ) {

      // try to get a reference to the basket Vector.
      Vector basket = (Vector)session.getValue("basket");

      // If basket is null, create one
      if ( basket == null ) {

        basket = new Vector(5);
        session.putValue("basket", basket);
      }
      // Add the passed in movie to the basket.
      basket.addElement(movie);
    }
  }

  //Process the HTTP Get request
  public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType("text/html");

    // Get the Movie parameters passed in the request.
    String id = request.getParameter("id");
    String price = request.getParameter("price");
    String redirect_url = request.getParameter("trans");

    // We are not checking out.  We are only adding an
    // item to the basket and redirecting to our previous
    // TitleListServlet response.
    if ( id != null ) {

      // Create the movie
      Movie movie = new Movie();
      movie.setTitleId((new Integer(id)).intValue());
      movie.setPrice((new Double(price)).doubleValue());
      // Add the movie to the basket.
      addToBasket(movie, request);
      // redirect the browser to the calling page.
      response.sendRedirect(redirect_url);
    }
  }

  //Get Servlet information
  public String getServletInfo() {

    return "AddMovieServlet Information";
  }
}
