package com.ferienclub.leisure.esb;

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

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.custadmin.beans.CustomerPreferences;
import com.ferienclub.leisure.LeisureOffers;
import com.ferienclub.leisure.esb.messages.BookingRequest;
import com.ferienclub.leisure.esb.messages.LeisureQuery;

public class FacilitiesGateway {
	
	Logger log = Logger.getLogger(FacilitiesGateway.class);
	
	public void process(LeisureQuery query){
		log.info("Entering method process(LeisureQuery query)");
		try {
			MuleClient client = new MuleClient();
			List allOffers = new ArrayList();
			allOffers.addAll(sendRequest("vm://facility1",client,query.getPrefs()));
			allOffers.addAll(sendRequest("vm://facility2",client,query.getPrefs()));
			allOffers.addAll(sendRequest("vm://facility3",client,query.getPrefs()));
			allOffers.addAll(sendRequest("vm://facility4",client,query.getPrefs()));
			query.setLeisureOffers(allOffers);
		} catch (UMOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void process(BookingRequest request){
		log.info("Entering method process(BookingRequest request)");
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send(request.getOffer().getFacilityEndpointName(),new Object[]{request.getOffer(),
				        new Integer(request.getNumberOfPersons())},null);
			Integer i = (Integer)result.getPayload();
			int a = i.intValue();
			if (a > 0) request.setSuccessful(true);
			else request.setSuccessful(false);
		} catch (UMOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private List sendRequest(String url, MuleClient client, CustomerPreferences prefs) throws UMOException{
		log.info("Entering private method sendRequest(...)");
		UMOMessage result = client.send(url,prefs,null);
		Object src = result.getPayload();
		LeisureOffers offers = null;
		if (src instanceof LeisureOffers)
			offers = (LeisureOffers)src;
		return offers.getOffers();
	}

}
