package com.ferienclub.mb;

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

import org.apache.log4j.Logger;
import org.mule.extras.client.MuleClient;
import org.mule.impl.RequestContext;
import org.mule.umo.UMOEventContext;
import org.mule.umo.UMOException;
import org.mule.umo.UMOMessage;

import com.ferienclub.mb.interfaces.IGetBookingPM;
import com.ferienclub.vacancymgm.beans.Booking;

public class GetBookingsPM implements IGetBookingPM {

	Logger log = Logger.getLogger(GetBookingsPM.class); 
	
	private Booking[] filterBookings(Booking[] bookings){
		List l = new ArrayList();
		for (int i = 0; i < bookings.length; i++)
		{
			Booking b = bookings[i];
			if (b.getStatus().equals("OPEN") || b.getStatus().equals("ACTIVE"))
			{
				l.add(b);
			}
		}
		Booking[] returnValue = new Booking[l.size()];
		int i = 0;
		for (Iterator itor = l.iterator(); itor.hasNext();)
		{
			returnValue[i] = (Booking)itor.next();
			i++;
		}
		return returnValue;
	}
	
	public Booking[] getBookings(String dummy) {
		log.info(this.getClass() + " : Entering method getBookings()");
		UMOEventContext context = RequestContext.getEventContext();
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/VacancyManagement?method=getBookings","",null);
			// UMOMessage result = context.sendEvent(roomId);
			Booking[] bookings = (Booking[])result.getPayload();
			log.info(this.getClass() + " : Received " + bookings.length + " Bookings");
			context.setStopFurtherProcessing(true);
			return filterBookings(bookings);
		} catch (UMOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Booking[] getBookings4Room(String roomId) {
		log.info(this.getClass() + " : Entering method getBookings4Room(\"" + roomId + "\")");
		UMOEventContext context = RequestContext.getEventContext();
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/VacancyManagement?method=getBookings4Room",roomId,null);
			// UMOMessage result = context.sendEvent(roomId);
			Booking[] bookings = (Booking[])result.getPayload();
			log.info(this.getClass() + " : Received " + bookings.length + " Bookings for Room " + roomId);
			context.setStopFurtherProcessing(true);
			return filterBookings(bookings);
		} catch (UMOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
