package com.ferienclub.pda.actions;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.mule.extras.client.MuleClient;
import org.mule.umo.UMOException;
import org.mule.umo.UMOMessage;

import com.ferienclub.custadmin.beans.User;
import com.ferienclub.leisure.LeisureOffer;
import com.ferienclub.leisure.esb.messages.BookingRequest;
import com.ferienclub.pda.forms.BookingForm;

public class BookingAction extends Action {

	Logger log = Logger.getLogger(BookingAction.class); 
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		log.info("Entering BookingAction");
		ActionErrors errors = new ActionErrors();
		BookingForm bForm = (BookingForm)form;
		int index = Integer.parseInt(bForm.getBookingIndex());
		
		User currentUser = (User)request.getSession().getAttribute("user");
		List leisureOffers = (List)request.getSession().getAttribute("offers");
		LeisureOffer offer = (LeisureOffer)leisureOffers.get(index);
		Boolean withCar = new Boolean(bForm.getWithCar());
		
		Object[] args = new Object[]{offer,currentUser.getUserId(),new Integer(offer.getNumberOfPersons()), withCar};
		
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/LeisureManagement?method=makeBooking", args, null);
			if (result == null)
			{
				errors.add("errors",new ActionError("could.not.make.booking"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			BookingRequest req = (BookingRequest)result.getPayload();
			if (!(req.isSuccessful()))
			{
				errors.add("errors",new ActionError("could.not.make.booking"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			request.setAttribute("message","Successfully made a booking for " + offer.getName());
		} catch (UMOException e) {
			e.printStackTrace();
			errors.add("errors",new ActionError("technical.error.mule"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		return mapping.findForward("success");
	}
	
}















