package com.ferienclub.admin.actions;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
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.MuleException;
import org.mule.extras.client.MuleClient;
import org.mule.umo.UMOMessage;

import com.ferienclub.admin.forms.AppointmentForm;
import com.ferienclub.custadmin.beans.Appointment;
import com.ferienclub.custadmin.beans.Place;
import com.ferienclub.custadmin.beans.User;

public class CreateAppointmentAction extends Action {

	Logger log = Logger.getLogger(CreateAppointmentAction.class); 
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		String mode = request.getParameter("mode");
		ActionErrors errors = new ActionErrors();
		if (mode.equals("init")){
			try {
				// Places auslesen
				MuleClient client = new MuleClient();
				UMOMessage result = client.send("axis:http://localhost:8081/axis/services/UserManagementPM?method=getPlaces","",null);
				Place[] places = (Place[])result.getPayload();
				log.info(this.getClass() + " : Received " + places.length + " places");
				List p = new ArrayList();
				for (int i = 0; i < places.length; i++)	p.add(places[i]);
				request.getSession().setAttribute("places",p);
				return mapping.findForward("initSuccess");
			} catch (Exception e){
				errors.add("technical Error",new ActionError("technical.error.mule"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
		}
		
		if (mode.equals("save")){
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
				AppointmentForm af = (AppointmentForm)form;
				Date d = null;
				// Check for correct date
				try {
					d = sdf.parse(af.getDate());
				} catch (NumberFormatException e) {
					errors.add("wrong date",new ActionError("wrong.date.format"));
					super.saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				}
				int duration;
				// Check for correct duration
				try {
					duration = Integer.parseInt(af.getDuration());
				} catch (NumberFormatException e) {
					errors.add("wrong duration",new ActionError("wrong.duration.format"));
					super.saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				}
				// Get the detailed user from the session
				User leadingUser = null;
				for (Iterator itor = ((List)request.getSession().getAttribute("users")).iterator(); itor.hasNext();){
					User u = (User)itor.next();
					if (u.getUserId().equals(af.getUserId())) leadingUser = u;
				}
				// Get the detailed place from the session
				Place place = null;
				for (Iterator itor = ((List)request.getSession().getAttribute("places")).iterator(); itor.hasNext();){
					Place p = (Place)itor.next();
					if (p.getPlaceId().equals(af.getPlaceId())) place = p;
				}
				// Create new Appointment and enter previously determined values
				if (place == null)
				{
					errors.add("error",new ActionError("no.place.selected"));
					super.saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				}
				Appointment a = new Appointment();
				a.setCategory(af.getCategory());
				a.setDatetime(d);
				a.setDuration(duration);
				a.setLeadingUser(leadingUser);
				a.setPlace(place);
				a.setSubject(af.getSubject());
				a.setUsers(new ArrayList());
				// Contact MULE to save the appointment
				MuleClient client = new MuleClient();
				UMOMessage result = client.send("axis:http://localhost:8081/axis/services/UserManagementPM?method=insertAppointment",a,null);
				int ok = ((Integer)result.getPayload()).intValue();
				if (ok < 0){
					log.info(this.getClass() + " : Could not insert new Appointment");
					errors.add("error inserting appointment",new ActionError("could.not.create.appointment"));
					super.saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				} 
				return mapping.findForward("saveSuccess");
			} catch (Exception e){
				errors.add("technical Error",new ActionError("technical.error.mule"));
				super.saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
		}
		errors.add("error",new ActionError("wrong.action.semantic"));
		super.saveErrors(request,errors);
		return (new ActionForward(mapping.getInput()));	
	}
}
