package com.ferienclub.pda.actions;

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;

public class CustomerPreferencesAction extends Action {

	Logger log = Logger.getLogger(CustomerPreferencesAction.class); 
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		log.info("Entering CustomerPreferencesAction");
		ActionErrors errors = new ActionErrors();
		// Fetching the current preferences from the database
		try {
			MuleClient client = new MuleClient();
			UMOMessage resp = client.send("axis:http://localhost:8081/axis/services/UserManagementPM?method=getPreferenceNames","",null);
			if (resp == null){
				errors.add("errors",new ActionError("no.preferences.in.database"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			String[] names = (String[])resp.getPayload();
			if (names.length == 0){
				// Create some preferences in case of no prefs in the database.
				names = new String[]{"museum","outdoor","restaurant","sightseeing"};
			}
			request.getSession().setAttribute("prefs",names);
			
		} catch (UMOException e) {
			e.printStackTrace();
			errors.add("errors",new ActionError("technical.error.mule"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		} catch (Exception e) {
			e.printStackTrace();
			errors.add("errors",new ActionError("technical.error"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		return mapping.findForward("success");
	}
	
}
