package com.cronos.admin.login;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.cronos.admin.services.ConfigurationBean;
import com.cronos.admin.services.ConfigurationService;

public class LoginAction extends DispatchAction {

	public ActionForward show(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		request.getSession().invalidate();
		request.getSession(false);

		return (mapping.findForward("show"));
	}

	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		@SuppressWarnings("unused")
		ResourceBundle rb = ResourceBundle.getBundle("com.cronos.admin.resources.MessageResources",
				this.getLocale(request));
		LoginForm formulario = (LoginForm) form;

		String relativeWebPath = "/WEB-INF";
		String absoluteDiskPath = getServlet().getServletContext().getRealPath(relativeWebPath);

		ConfigurationBean conf = ConfigurationService.readXMLConfiguration(absoluteDiskPath);

		if (formulario.getLogin().equals(conf.getLogin()) && formulario.getClave().equals(conf.getClave())) {
			request.getSession().setAttribute("validsession", Boolean.valueOf(true));
			return (mapping.findForward("loginok"));
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("clave", new ActionMessage("error.LoginUsuarioClaveIncorrecta"));
			this.addErrors(request, errors);
			return (mapping.findForward("show"));
		}
	}
}