package com.ferienclub.ta.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

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.ta.forms.DetailBookingForm;
import com.ferienclub.vacancymgm.beans.Booking;
import com.ferienclub.vacancymgm.beans.Room;

public class RoomDetailAction extends Action{

	Logger log = Logger.getLogger(RoomListingAction.class);
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		ActionErrors errors = new ActionErrors();
		DetailBookingForm dbf = (DetailBookingForm)form;
		String roomId = dbf.getRoomId();
		HttpSession session = request.getSession();
		List rooms = (List)session.getAttribute("rooms");
		Room room4Detail = getRoomFromCache(roomId,rooms);
		if (room4Detail == null){
			errors.add("roomNotFound", new ActionError("no.room.found"));
			saveErrors(request, errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		// Contact the club and get all bookings for this room
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/GetBookingsPM?method=getBookings4Room",room4Detail.getRoomId(),null);
			Booking[] bookings = (Booking[])result.getPayload(); 
			System.out.println("Received " + bookings.length + " bookings for room " + room4Detail.getRoomId());
			List bookings4Page = new ArrayList();
			for (int i = 0; i < bookings.length; i++)
				bookings4Page.add(bookings[i]);
			request.setAttribute("bookings",bookings4Page);
			request.setAttribute("room",room4Detail);
		} catch (UMOException e) {
			errors.add("technicalError",new ActionError("technical.error.mule"));
			saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		} catch (Exception e){
			errors.add("technicalError",new ActionError("technical.error"));
			saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		return mapping.findForward("success");
	}
	
	public static Room getRoomFromCache(String roomId, List rooms){
		Room room4Detail = null;
		for (Iterator itor = rooms.iterator(); itor.hasNext();)
		{
			Room r = (Room)itor.next();
			if (r.getRoomId().equals(roomId)) room4Detail = r;
		}
		return room4Detail;
	}
	
}
