package com.ferienclub.pda.actions;

import java.util.StringTokenizer;

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.UMOException;
import org.mule.umo.UMOMessage;

import com.ferienclub.custadmin.beans.User;
import com.ferienclub.pda.forms.LoginForm;

public class LoginAction extends Action {

    Logger log = Logger.getLogger(LoginAction.class); 
	
	public ActionForward perform(ActionMapping mapping,
			 ActionForm form,
			 HttpServletRequest request,
			 HttpServletResponse response){
		
		log.info("Entering LoginAction");
		ActionErrors errors = new ActionErrors();
		LoginForm loginForm = (LoginForm)form;
		String name = loginForm.getName(), password = loginForm.getPassword(), firstName = "", lastName = "";
		StringTokenizer tok = new StringTokenizer(name);
		// Check for user entered no name
		if (name.equals("") || name == null)
		{
			errors.add("errors",new ActionError("must.enter.name"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		// Check for user entered no password
		if (password == null) password = "";
		// Extract firstName
		firstName = tok.nextToken();
		// Extract lastName
		while (tok.hasMoreTokens())
		{
			lastName += tok.nextToken() + " ";
		}
		lastName = lastName.trim();
		
		// Call MULE and try to login
		try {
		   MuleClient client = new MuleClient();
		   log.info("Trying to login user: " + firstName + " " + lastName + " with password: \"" + password + "\"");
		   Object args[] = new Object[]{new String(firstName),new String(lastName), new String(password)};
		   UMOMessage answer = client.send("axis:http://localhost:8081/axis/services/UserManagementPM?method=login",args,null);
		   
		   if (answer == null){
			   errors.add("technical Error",new ActionError("login.failed"));
			   super.saveErrors(request,errors);
			   return (new ActionForward(mapping.getInput()));
		   }
		   Object o = answer.getPayload();
		   User u = (User)o;
		   request.getSession().setAttribute("user",u);
		} catch (UMOException e){
			errors.add("technical Error",new ActionError("technical.error.mule"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		} catch (ClassCastException e){
			errors.add("technical Error",new ActionError("technical.error"));
			super.saveErrors(request,errors);
			return (new ActionForward(mapping.getInput()));
		}
		
		return mapping.findForward("success");
	}
	
}
