/**
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 -
 - JASS: Java Advanced tranSaction Support
 -
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 -
 - This module was originally developed by 
 -
 -    LSD (Distributed Systems Lab, http://lsd.ls.fi.upm.es/lsd/lsd.htm)
 -    at Universidad Politecnica de Madrid (UPM) as an ObjectWeb Consortium
 -    (http://www.objectweb.org) project.
 -
 -    This project has been partially funded by the European Commission under
 -    the IST programme of V FP grant IST-2001-37126 and by the Spanish
 -    Ministry of Science & Technology (MCyT) grants TIC2002-10376-E and
 -    TIC2001-1586-C03-02
 -
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 -  The original code and portions created by LSD are 
 -  Copyright (c) 2004 LSD (UPM)  
 -  All rights reserved.
 -  
 - Redistribution and use in source and binary forms, with or without 
 - modification, are permitted provided that the following conditions are met:
 -
 - -Redistributions of source code must retain the above copyright notice, this
 - list of conditions and the following disclaimer. 
 -
 - -Redistributions in binary form must reproduce the above copyright notice, 
 - this list of conditions and the following disclaimer in the documentation 
 - and/or other materials provided with the distribution. 
 -
 - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
 - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 - POSSIBILITY OF SUCH DAMAGE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 -
 -  Author: Francisco Perez Sorrosal (frperezs)
 -
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.objectweb.jass.examples.travelagency.servlets;

import org.objectweb.jass.examples.travelagency.ejbs.AirlineHome;
import org.objectweb.jass.examples.travelagency.ejbs.Airline;
import org.objectweb.jass.examples.travelagency.ejbs.HotelHome;
import org.objectweb.jass.examples.travelagency.ejbs.Hotel;
import org.objectweb.jass.examples.travelagency.ejbs.TravelAgency;
import org.objectweb.jass.examples.travelagency.ejbs.TravelAgencyHome;
import org
	.objectweb
	.jass
	.examples
	.travelagency
	.exceptions
	.NotEnoughSeatsException;
import org
	.objectweb
	.jass
	.examples
	.travelagency
	.exceptions
	.NotEnoughRoomsException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.ejb.CreateException;
import javax.activity.opennested.UserOpenNested;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.sql.SQLException;

/**
 * Creates the application web interface by invoking the corresponding EJBs 
 * (TravelAgencyEJB, AirlineEJB and HotelEJB).
 * @author fran
 * Date: Feb 16, 2004
 * org.objectweb.jass.examples.travelagency.servletsReservationServlet.java
 */
public class ReservationServlet extends HttpServlet {
	private AirlineHome airlineHome;
	private Airline airline;
	private HotelHome hotelHome;
	private Hotel hotel;
	private TravelAgencyHome travelAgencyHome;
	private TravelAgency travelAgency;
	private UserOpenNested uon;

	/**
	 * Invokes methods to obtain the required EJBs references
	 * (TravelAgencyEJB, AirlineEJB and HotelEJB).
	 */
	public void init() {
		getAdaptAirlineEJB();
		getAdaptHotelEJB();
		getAdaptTravelAgencyEJB();
		System.out.println("Init called!!!");
	}

	/**
	 * Executed on servlet destruction.
	 */
	public void destroy() {
		System.out.println("Destroy called!!!");
	}

	/**
	 * Servlet main method.
	 */
	public void service(HttpServletRequest req, HttpServletResponse res)
		throws IOException {
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		out.println(
			"<HTML><HEAD></HEAD><BODY>"
				+ "<H1><U>ADAPT RESERVATION SERVICE</U></H1>");

		String action = req.getParameter("action");
		if (action == null) {
			try {
				showFlightInfo(out);
				showHotelInfo(out);
				showRequest(out);
			} catch (SQLException e) {
				out.println(
					"<H2><FONT COLOR=\"red\">Database ERROR!!!" + "</FONT></H2>");
			}
		} else {
			if (action.equals("reserve")) {
				String name = req.getParameter("name");
				String nSeats = req.getParameter("number_of_seats");
				String nRooms = req.getParameter("number_of_rooms");
				makeReservation(
					out,
					name,
					Integer.parseInt(nSeats),
					Integer.parseInt(nRooms));
			}
		}
		insertReturn(out);
		out.println("</BODY></HTML>");
	}

	/**
	 * Shows the number of free seats in the flight.
	 * @param out
	 */
	private void showFlightInfo(PrintWriter out) throws SQLException {
		int freeSeats = 0;

		try {
			freeSeats = airline.getFreeSeats();
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		out.println(
			"<CENTER><H3>Flight Info (ADPT001):</H3>"
				+ "<FONT COLOR=\"red\"><U>Free</U> seats in flight: </FONT>"
				+ freeSeats
				+ "</CENTER><HR SIZE=3>");
	}

	/**
	 * Shows the number of free rooms in the hotel.
	 * @param out
	 */
	private void showHotelInfo(PrintWriter out) throws SQLException {
		int freeRooms = 0;

		try {
			freeRooms = hotel.getFreeRooms();
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		out.println(
			"<CENTER><H3>Hotel Info (ADAPT PALACE *****):</H3>"
				+ "<FONT COLOR=\"red\"><U>Free</U> rooms in hotel: </FONT>"
				+ freeRooms
				+ "</CENTER><HR SIZE=3>");
	}

	/**
	 * Shows application instructions and reservation request form.
	 * @param out
	 */
	private void showRequest(PrintWriter out) {
		out.println(
			"<BR><FONT COLOR=\"red\"><U>Instructions:</U></FONT> Please, "
				+ "insert below your name and the number of seats "
				+ "and rooms that you want to reserve. If it is possible, the system "
				+ "will made the corresponding reserves for you -attending to the "
				+ "values shown above- and it will report to you the results or any "
				+ "possible failure.<BR><BR>");
		out.println(
			"<FORM METHOD=\"POST\" ACTION=\"reservation\"> "
				+ "<H3>Reservation Info:</H3>"
				+ "Reservation Name:<INPUT TYPE=\"TEXT\" NAME=\"name\"><BR><BR>"
				+ "Flight info (Number of seats): <INPUT TYPE=\"TEXT\" NAME=\"number_of_seats\"><BR>"
				+ "Hotel info (Number of rooms): <INPUT TYPE=\"TEXT\" NAME=\"number_of_rooms\"><BR>"
				+ "<INPUT TYPE=\"HIDDEN\" NAME=\"action\" VALUE=\"reserve\">"
				+ "<BR><INPUT TYPE=\"RESET\" VALUE=\"Clear\">"
				+ "<INPUT TYPE=\"SUBMIT\" VALUE=\"Send\">"
				+ "</FORM>");
		out.println("</CENTER><HR SIZE=3>");
	}

	/**
	 * Inserts the a form with a button to return to the main application page.
	 * @param out
	 */
	private void insertReturn(PrintWriter out) {
		out.println(
			"<FORM METHOD=\"POST\" ACTION=\"reservation\"> "
				+ "<INPUT TYPE=\"SUBMIT\" VALUE=\"Go Reservation Page\"> "
				+ "</FORM>");
	}

	/**
	 * Gets the reference to the Airline EJB.
	 */
	private void getAdaptAirlineEJB() {
		Object obj = null;
		Context ctx = null;
		try {
			ctx = new InitialContext();
			obj = ctx.lookup("AirlineEJB");
			airlineHome =
				(AirlineHome) javax.rmi.PortableRemoteObject.narrow(
					obj,
					AirlineHome.class);
			airline = airlineHome.create();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (CreateException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Gets the reference to the Hotel EJB.
	 */
	private void getAdaptHotelEJB() {
		Object obj = null;
		Context ctx = null;
		try {
			ctx = new InitialContext();
			obj = ctx.lookup("HotelEJB");
			hotelHome =
				(HotelHome) javax.rmi.PortableRemoteObject.narrow(
					obj,
					HotelHome.class);
			hotel = hotelHome.create();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (CreateException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Gets the reference to the TravelAgency EJB.
	 */
	private void getAdaptTravelAgencyEJB() {
		Object obj = null;
		Context ctx = null;
		try {
			ctx = new InitialContext();
			obj = ctx.lookup("TravelAgencyEJB");
			travelAgencyHome =
				(TravelAgencyHome) javax.rmi.PortableRemoteObject.narrow(
					obj,
					TravelAgencyHome.class);
			travelAgency = travelAgencyHome.create();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (CreateException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Invokes the reservation method on the TravelAgency EJB showing
	 * the results. 
	 * @param out
	 * @param name
	 * @param nSeats
	 * @param nRooms
	 */
	private void makeReservation(
		PrintWriter out,
		String name,
		int nSeats,
		int nRooms) {
		try {
			travelAgency.makeReservation(name, nSeats, nRooms);
			out.println(
				"<CENTER><H2>Congratulations!!!</H2>"
					+ "<H3>Customer <FONT COLOR=\"red\">"
					+ name
					+ "</FONT> has reserved <FONT COLOR=\"red\">"
					+ nSeats
					+ "</FONT> seats and <FONT COLOR=\"red\">"
					+ nRooms
					+ "</FONT> rooms</H3></CENTER>");
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotEnoughSeatsException e) {
			out.println(
				"<CENTER><H2>An ERROR has occurred!!!</H2><BR>"
					+ "<H3><FONT COLOR=\"red\">Not enough seats in flight!!!</FONT></H3></CENTER>");
		} catch (NotEnoughRoomsException e) {
			out.println(
				"<CENTER><H2>An ERROR has occurred!!!</H2><BR>"
					+ "<H3><FONT COLOR=\"red\">Not enough rooms in hotel!!!</FONT></H3></CENTER>");
		} catch (SQLException e) {
			out.println(
				"<H2><FONT COLOR=\"red\">Database ERROR!!!" + "</FONT></H2>");
		} catch (Exception e) {
			out.println(
				"<H2><FONT COLOR=\"red\">Unespected ERROR!!!" + "</FONT></H2>");
		}
	}
}
