/*
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Struts", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package es.ejie.frmk.presentacion.iu.taglib.html;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;
import java.util.MissingResourceException;

import javax.servlet.jsp.JspException;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;

import es.ejie.frmk.infraestructura.traza.Q70TraceLevel;
import es.ejie.frmk.infraestructura.traza.Q70Traza;
import es.ejie.frmk.presentacion.validacion.Q70ValidacionesGenericasPlugIn;

/**
 * Custom tag that renders error messages if an appropriate request attribute
 * has been created.  The tag looks for a request attribute with a reserved
 * key, and assumes that it is either a String, a String array, containing
 * message keys to be looked up in the module's MessageResources, or
 * an object of type <code>org.apache.struts.action.ActionErrors</code>.
 * <p>
 * The following optional message keys will be utilized if corresponding
 * messages exist for them in the application resources:
 * <ul>
 * <li><b>errors.header</b> - If present, the corresponding message will be
 *     rendered prior to the individual list of error messages.</li>
 * <li><b>errors.footer</b> - If present, the corresponding message will be
 *     rendered following the individual list of error messages.</li>
 * <li><b>errors.prefix</b> - If present, the corresponding message will be
 *     rendered before each individual error message.</li>
 * <li><b>errors.suffix</b> - If present, the corresponding message will be
 *     rendered after each individual error message.</li>
 * </ul>
 *
 * @author UFRM002
 */
public class Q70ErrorsTag extends Q70BaseHandlerTag 
{
	/**
	 * Instancia del log de trazas
	 */
	private static Q70Traza tr = Q70Traza.getSingleton();
	
    // ----------------------------------------------------------- Properties

    /**
     * The default locale on our server.
     * @deprecated Use Locale.getDefault() directly.
     */
    protected static Locale defaultLocale = Locale.getDefault();

    /**
     * The line ending string.
     */
    protected static String lineEnd = System.getProperty("line.separator");


	/**
	 * Clave de session que tiene el Locale para el idioma de los datos de resultado.
	 */
/*	
	private String localeKey = Globals.LOCALE_KEY;

	public String getLocale() {
		return (this.localeKey);
	}

	public void setLocale(String locale) {
		this.localeKey = locale;
	}
*/

    /**
     * The request attribute key for our error messages (if any).
     */
    protected String name = Globals.ERROR_KEY;

    public String getName() {
        return (this.name);
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * The name of the property for which error messages should be returned,
     * or <code>null</code> to return all errors.
     */
    protected String property = null;

    public String getProperty() {
        return (this.property);
    }

    public void setProperty(String property) {
        this.property = property;
    }

    // ------------------------------------------------------- Public Methods

    /**
     * Render the specified error messages if there are any.
     *
     * @exception JspException if a JSP exception has occurred
     */
    public int doStartTag() throws JspException 
    {
		if (tr.isTraceActive())	tr.trace(COMPONENTE, Q70TraceLevel.DEBUG, "Generando tag de tipo " + this.getClass().toString());

		setListaI18nKey(new ArrayList(3));
		// Were any error messages specified?
        ActionErrors errors = null;
        try {
            errors = RequestUtils.getActionErrors(pageContext, name);
        } catch (JspException e) {
            RequestUtils.saveException(pageContext, e);
            throw e;
        }

        if ((errors == null) || errors.isEmpty()) {
            return (1); //EVAL_BODY_INCLUDE
        }


        // Render the error messages appropriately
        StringBuffer results = new StringBuffer();
        boolean headerDone = false;
        String message = null;
        Iterator reports = (property == null) ? errors.get() : errors.get(property);

		while (reports.hasNext()) 
		{
			ActionError report = (ActionError) reports.next();
			if (!headerDone) 
			{
				
				message = getKeyMessage("errors.header");                            
	        	if (null!=message && 0<message.length()) 
	        	{
					results.append(message);
					results.append(lineEnd);
				}
				headerDone = true;
			}
			
			message = getKeyMessage("errors.prefix");        
			if (null!=message && 0<message.length())
				results.append(message);
		    
			
			Object[] argumentosMensaje = report.getValues();
			
			if ( report.getValues() != null && argumentosMensaje.length>0 && argumentosMensaje[0] instanceof Q70ValidacionesGenericasPlugIn ){
				ArrayList listaMenssajesKey = new ArrayList(argumentosMensaje.length);
				Q70ValidacionesGenericasPlugIn plugIn = (Q70ValidacionesGenericasPlugIn)argumentosMensaje[0];
				
		    	ArrayList lista = new ArrayList(1);
		    	lista.add(plugIn.getI18nKey());				    	

				//Obtener el objeto Locale para la clave de session especificada.
				Locale userLocale = RequestUtils.retrieveUserLocale(pageContext, super.getLocale()); 		
				
				for (int i=1; i < argumentosMensaje.length; i++){
				    try{
						//Obtener el mensaje llamando al Gestor de Mensajes e Internacionalizacion
				    	if (argumentosMensaje[i] != null){
					    	listaMenssajesKey.add(getI18nMessage(lista, argumentosMensaje[i].toString(),userLocale.getLanguage(),null));
				    	}
				    }
				    catch(MissingResourceException mre)
				    {
				    	listaMenssajesKey.add(argumentosMensaje[i].toString());
				    }
				}
				
				if (!listaMenssajesKey.isEmpty()){
					argumentosMensaje = new Object[listaMenssajesKey.size()];
					Iterator it = listaMenssajesKey.iterator();
					int i = 0;
					while (it.hasNext()) {
						Object element = (Object) it.next();
						argumentosMensaje[i++]= element;					
					}
				}
			}
			    		
		    try
		    {
				//Obtener el mensaje llamando al Gestor de Mensajes e Internacionalizacion 
				message = getMessage(report.getKey(), argumentosMensaje );
		    }
		    catch(MissingResourceException mre)
		    {
		    	message = report.getKey();
		    }
			if (null!=message && 0<message.length())
			{
                results.append(message);
                results.append(lineEnd);
            }

			message = getKeyMessage("errors.suffix");
			
			if (null!=message && 0<message.length())
                results.append(message);
        }
        
		message = getKeyMessage("errors.footer");        
        if (headerDone && (null!=message && 0<message.length())) 
        {
            results.append(message);
            results.append(lineEnd);
        }
        
        ResponseUtils.write(pageContext, results.toString());

        return (1); //EVAL_BODY_INCLUDE

    }

    /**
     * Release any acquired resources.
     */
    public void release() {
        super.release();
        name = Globals.ERROR_KEY;
        property = null;
    }


	//-------------------------------------------------------------------------------- Private methods
     
	/**
	 * Recupera un mensaje llamando al Gestor de Mensajes e Internacionalizacion 
	 * @param (String) key: clave del mensaje a buscar.
	 * @param (Object[]) args: argumentos del texto del mensaje
	 * @return (String): texto del mensaje.
	 */
	private String getMessage(String key, Object[] args ) 
		throws JspException
	{

		//Obtener el objeto Locale para la clave de session especificada.
		Locale userLocale = RequestUtils.retrieveUserLocale(pageContext, super.getLocale()); 		

		//Obtener el mensaje llamando al Gestor de Mensajes e Internacionalizacion 
		String mensaje = getI18nMessage( super.getListaI18nKey(), 
										 key, 
										 userLocale.getLanguage(),
										 args );										 
		return mensaje;    	
	}
	
	
	/**
	 * Recupera el mensaje llamando al Gestor de Mensajes e Internacionalizacion.
	 * Si no se encuentra, captura la excepcion y devuelve null.
	 * @param (String) key: clave del mensaje a buscar.
	 * @return (String): texto del mensaje o null si no se encuentra.
	 */
	private String getKeyMessage(String key)
		throws JspException
	{
		String msg = null;
		
		try
		{
			//Obtener el mensaje llamando el metodo con los parametros correctos.
			msg = getMessage(key, null);
		}
		catch(MissingResourceException mre)
		{ }
		
		return msg;		
	}
	

}
