package com.ferienclub.admin.actions;

import java.sql.Savepoint;

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.admin.forms.PlaceForm;
import com.ferienclub.custadmin.beans.Place;

public class CreatePlaceAction extends Action {

public static Logger log = Logger.getLogger(InitPlacesAdmAction.class);
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		ActionErrors errors = new ActionErrors();
		
		log.info(this.getClass() + " : Entering method perform");
		
		String mode = request.getParameter("mode");
		if (mode.equals("save"))
		{
			PlaceForm pf = (PlaceForm)form;
			Place p = new Place();
			try 
			{
				p.setLatitude(Float.parseFloat(pf.getLatitude()));
				p.setLongitude(Float.parseFloat(pf.getLongitude()));
				p.setValidRange(Float.parseFloat(pf.getValidRange()));
				p.setName(pf.getName());
				
				try {
					MuleClient client = new MuleClient();
					UMOMessage result = client.send("axis:http://localhost:8081/axis/services/UserManagementPM?method=addPlace",p,null);
					int rv = ((Integer)result.getPayload()).intValue();
					if (rv < 0)
					{
						log.info(this.getClass() + " : Error creating Place");
						errors.add("error1",new ActionError("could.not.create.place"));
						super.saveErrors(request,errors);
						return (new ActionForward(mapping.getInput()));
					} 
					else 
					{
						log.info(this.getClass() + " : Successfully created Place");
					}
				} catch (UMOException e) {
					log.info(this.getClass() + " : Technical Error!");
					errors.add("error1",new ActionError("technical.error.mule"));
					super.saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				}
			}
			  catch (NumberFormatException e)
			{
			  
			}
		}
		
		if (mode.equals("init")){
			return mapping.findForward("createPlacePage");
		}
		
		return mapping.findForward("success");
	}
	
}
