package com.ferienclub.ta.actions;

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

import com.ferienclub.custadmin.beans.Address;
import com.ferienclub.custadmin.beans.User;
import com.ferienclub.ta.forms.DetailBookingForm;
import com.ferienclub.vacancymgm.beans.Booking;
import com.ferienclub.vacancymgm.beans.Room;

public class BookingAction extends Action {

	public static Logger log = Logger.getLogger(RoomListingAction.class);
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		ActionErrors errors = new ActionErrors();
		DetailBookingForm bdf = (DetailBookingForm)form;
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
		String action = request.getParameter("action");
		
		if (action.equals("makeBooking"))
		{
			log.info("action == makeBooking");
			// Create user with address and a booking object
			Booking b = new Booking();
			List persons = (List)request.getSession().getAttribute("persons");
			if (persons == null || persons.size() == 0)
			{
				request.setAttribute("room",RoomDetailAction.getRoomFromCache(bdf.getRoomId(),(List)request.getSession().getAttribute("rooms")));
				errors.add("error",new ActionError("need.to.add.person"));
				saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			try {
				b.setFromDate(sdf.parse(bdf.getFrom()));
				b.setToDate(sdf.parse(bdf.getTo()));
			} catch (ParseException e) {
				request.setAttribute("room",RoomDetailAction.getRoomFromCache(bdf.getRoomId(),(List)request.getSession().getAttribute("rooms")));
				errors.add("wrongDateFormat",new ActionError("wrong.date.format"));
				saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			List bookedRoomsIds = new ArrayList();
			bookedRoomsIds.add(bdf.getRoomId());
			b.setBookingUser((User)persons.get(0)); // Assume the first user entered is the bookingUser
			b.setUsers(persons);
			b.setRoomsIds(bookedRoomsIds);
			b.setStatus("OPEN");
			
			System.out.println("\n\nInhalt der UserListe:\n\n");
			for (Iterator itor = b.getUsers().iterator(); itor.hasNext();)
			{
				User us = (User)itor.next();
				System.out.println(us.getFirstName() + " " + us.getName());
			}
			System.out.println("\n\n");
			try {
				MuleClient client = new MuleClient();
				UMOMessage result = client.send("axis:http://localhost:8081/axis/services/MakeBookingPM?method=makeBooking",b,null);
				Integer ok = (Integer)result.getPayload();
				if (ok.intValue() <= 0){
					errors.add("technicalError",new ActionError("booking.not.successful"));
					saveErrors(request,errors);
					return (new ActionForward(mapping.getInput()));
				}
			} catch (UMOException e) {
				request.setAttribute("room",RoomDetailAction.getRoomFromCache(bdf.getRoomId(),(List)request.getSession().getAttribute("rooms")));
				errors.add("technicalError",new ActionError("technical.error.mule"));
				saveErrors(request,errors);
				return (new ActionForward(mapping.getInput()));
			}
			request.getSession().removeAttribute("persons");
			request.getSession().removeAttribute("room");
			return mapping.findForward("bookingSuccess");
		}
		
		if (action.equals("init")){
			log.info("action == init");
			Room r = RoomDetailAction.getRoomFromCache(bdf.getRoomId(),(List)request.getSession().getAttribute("rooms"));
			request.getSession().setAttribute("room",r);
			request.getSession().setAttribute("persons",new java.util.ArrayList());
			return mapping.findForward("initSuccess");
		}
		
		if (action.equals("addUser")){
			log.info("action == addUser");
			User u = extractUser(bdf);
			List persons = (List)request.getSession().getAttribute("persons");
			persons.add(u);
			request.getSession().setAttribute("persons",persons);
			return mapping.findForward("addUserSuccess");
		}
		
		return mapping.findForward("initSuccess");
	}
	
	private User extractUser(DetailBookingForm bdf){
		User u = new User();
		Address a = new Address();
		u.setFirstName(bdf.getFirstName());
		u.setName(bdf.getName());
		u.setPassword("STANDARD");
		a.setCountry(bdf.getCountry());
		a.setEmail(bdf.getEmail());
		a.setPhone(bdf.getPhone());
		a.setProvince(bdf.getProvince());
		a.setStreet(bdf.getStreet());
		a.setZipCode(bdf.getZipcode());
		u.setAddress(a);
		return u;
	}
	
}

