/**
 *
 */
package com.fp.frontend.utility;

import java.util.ResourceBundle;

import javax.faces.component.UIComponent;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.primefaces.component.datatable.DataTable;

/**
 * @author Gbensvides
 *
 */
public class LifeCicleListener implements PhaseListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private static ResourceBundle resource_bundleValidacion = ResourceBundle
            .getBundle("validation_es");

    /* (non-Javadoc)
	 * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
     */
    @Override
    public void afterPhase(PhaseEvent arg0) {
        // TODO Auto-generated method stub

    }

    /* (non-Javadoc)
	 * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     */
    @Override
    public void beforePhase(PhaseEvent arg0) {
        // TODO Auto-generated method stub
//		//System.out.println(arg0.getPhaseId().toString());
        if (arg0.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
            processViewTree(arg0.getFacesContext().getViewRoot());
        }
    }

    /* (non-Javadoc)
	 * @see javax.faces.event.PhaseListener#getPhaseId()
     */
    @Override
    public PhaseId getPhaseId() {
        // TODO Auto-generated method stub
        return PhaseId.ANY_PHASE;
    }

    private void processViewTree(UIComponent component) {

        // //System.out.println(component.getClientId() + " " + component.getClass() );
        for (UIComponent child : component.getChildren()) {

            ////System.out.println("+ " + child.getId() + " ["+child.getClass()+"]");
            if (child instanceof DataTable) {
                DataTable table = (DataTable) child;
                Object mensajeEmpty = table.getAttributes().get("emptyMessage");
                if (mensajeEmpty != null && mensajeEmpty.equals("No records found.")) {
                    table.getAttributes().put("emptyMessage", resource_bundleValidacion.getString("org.primefaces.component.datatable.emptyMesssage"));
                }
            }

            // Process next node
            processViewTree(child);
        }
    }

}
