package com.ferienclub.ta.actions;

import java.util.ArrayList;
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.ContactForm;
import com.ferienclub.vacancymgm.beans.Room;

public class RoomListingAction extends Action{

	Logger log = Logger.getLogger(RoomListingAction.class);
	
	public ActionForward perform(ActionMapping mapping,
								 ActionForm form,
								 HttpServletRequest request,
								 HttpServletResponse response){
							
		// Get the actionForm
		ActionErrors errors = new ActionErrors();
		
		HttpSession session = request.getSession();
		
		ContactForm cf = (ContactForm)form;
		String clubToContact = cf.getClubToContact();
		if (clubToContact.equals("Klub Robinson"))
		{
			log.info("Contacting Klub Robinson");
		} else {
			log.info("You are not contacting Klub Robinson ...");
			errors.add("no club selected", new ActionError("no.club.selected"));
			saveErrors(request, errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		/* Contacting the MULE Web-Service with the MULE-Client */
		try {
			MuleClient client = new MuleClient();
			UMOMessage result = client.send("axis:http://localhost:8081/axis/services/GetRoomsPM?method=getRooms","",null);
			Room[] rooms = (Room[])result.getPayload();
			log.info("Received " + rooms.length + " rooms from the club");
			System.out.println("Received " + rooms.length + " rooms from the club");
			List listWithRooms = new ArrayList();
			for (int i = 0; i < rooms.length; i++)
				listWithRooms.add(rooms[i]);
			session.setAttribute("rooms",listWithRooms);
		} catch (UMOException e) {
			errors.add("technicalError",new ActionError("technical.error.mule"));
			saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		return mapping.findForward("success");
	}
	
}
