/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listeners;

import java.io.IOException;
import java.io.PrintWriter;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Glavni Administrator
 */
public class MyPhaseListener implements PhaseListener {

    public void afterPhase(PhaseEvent pe) {
        FacesContext context = FacesContext.getCurrentInstance();
        //da li je ajax poziv pokrenuo jsf zivotni ciklus
        String ajaxParam =
                (String) context.getExternalContext().getRequestParameterMap().get("ajax");
       
        if ("true".equals(ajaxParam)) {
            boolean valid = true;
            //dohvatamo prosledjeni element forme zip
            String zipParam =
                    (String) context.getExternalContext().getRequestParameterMap().get("zip");
            //dohvatamo UIInput komponentu kako bi dosli do validatora
            UIViewRoot view = context.getViewRoot();
            UIInput zip = (UIInput) view.findComponent("forma:zip");
            if (zip != null) {
                HttpServletResponse response =
                        (HttpServletResponse) context.getExternalContext().getResponse();
                Validator[] validators = zip.getValidators();
                PrintWriter writer=null;
                try {
                    writer = response.getWriter();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                //validacija zip koda 
                for (int i = 0; i < validators.length; i++) {
                    try {
                        validators[i].validate(context, zip, zipParam);
                    } catch (ValidatorException ve) {
                        writer.write(ve.getMessage());
                        valid=false;
                        System.out.println("Nije Prosla validacija!!");
                        break;
                        
                    }
                }
                if(valid==true){ writer.write("okay");  System.out.println(" Prosla validacija!!");}
            }//kraj zip!=null
            //prekidamo dalji zivotni ciklus i odlazimo u 6 fazu render response
            context.responseComplete();   
        }//kraj ajax zahteva

    }

    public void beforePhase(PhaseEvent arg0) {
    }

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
