/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.faces.facelets.example.polling;

import com.icesoft.faces.facelets.component.util.Util;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import java.util.Random;


/**
 * <p>The PollingListener is responsible for handling the display
 * of a new view when doing some normal JSF request.
 * </p>
 *
 * @author ICEfaces Technologies Inc.
 */
public class PollingListener
        implements PhaseListener {

    public void beforePhase(PhaseEvent event) {

        // polling request check, check the request map to see if the hidden
        // polling field exists.
        String pollingRequest = Util.getRequestParameter("pollingRequest");
        boolean isPollingRequest = pollingRequest != null;

        if (isPollingRequest) {
            // EXECUTE MODEL LOGIC HERE TO UPDATE OUR VIEW.
            // get a reference to our example bean.
            PollingExampleBean pollingExampleBean =
                    (PollingExampleBean) Util.getManagedBean(
                            "pollingExampleBean");
            // randomly choose weather conditions.            
            Random generator = new Random();
            int randomIndex = generator.nextInt(7);
            pollingExampleBean.setWeather(PollingExampleBean.getWeatherTypes()[randomIndex]);
        }

    }

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

    // ignore, not needed for our implementation.
    public void afterPhase(PhaseEvent event) {
    }

}
