package org.icefaces.impl.application;

import org.icefaces.util.EnvUtils;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import static javax.faces.event.PhaseId.APPLY_REQUEST_VALUES;

public class PostbackValidator implements PhaseListener {

    public void afterPhase(PhaseEvent event) {
    }

    public void beforePhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        String httpMethod = EnvUtils.getSafeRequest(context).getMethod();
        if (EnvUtils.isPostValidationEnabled(context) && context.isPostback() && !"POST".equalsIgnoreCase(httpMethod)) {
            throw new InvalidPostbackRequest("Cannot have HTTP " + httpMethod + " request as postback.");
        }
    }

    public PhaseId getPhaseId() {
        return APPLY_REQUEST_VALUES;
    }

    public static class InvalidPostbackRequest extends RuntimeException {
        public InvalidPostbackRequest(String message) {
            super(message);
        }
    }
}
