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.esb.messages.LeisureQuery;

public class GetLeisureOffersAction extends Action {

	Logger log = Logger.getLogger(GetLeisureOffersAction.class); 
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		log.info("Entering GetLeisureOffersAction");
		
		ActionErrors errors = new ActionErrors();
		User currentUser = (User)request.getSession().getAttribute("user");
		
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/LeisureManagement?method=getLeisureOffers",currentUser.getUserId(),null);
			if (result == null){
				errors.add("errors",new ActionError("no.leisure.offers"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			LeisureQuery query = (LeisureQuery)result.getPayload();
			List offers = query.getLeisureOffers();
			if (offers == null){
				log.info("No Offers received from Message Bus");
				errors.add("errors",new ActionError("no.leisure.offers"));
				saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			if (offers.size() == 0){
				log.info("No Offers received from Message Bus");
				errors.add("errors",new ActionError("no.leisure.offers"));
				saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			log.info("Received " + offers.size() + " leisure offers from the message bus.");
			request.getSession().setAttribute("offers",offers);
		} 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");
	}
	
}
