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

import java.text.MessageFormat;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;


/**
 *
 * @author abderrahim.TOUAIBIA
 */
@Service
public final class UtilView {
    
    private static String MESSAGE = "exMessage";
    private static String error = "errorMSG";
    
    
    public static String urlParam(String param){
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
       return request.getParameter(param);
    }
    
    public static void setErrorMessage(String exMessage) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(MESSAGE, exMessage);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(error, true);
    }

    public static void setInfoMessage(String exMessage) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(MESSAGE, exMessage);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(error, false);
    }

    public static void reinitMessage() {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(MESSAGE, null);
    }

    public static void updateMessages(boolean update) throws Exception {
        String exMessage = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(MESSAGE);
        Boolean errorMSG = (Boolean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(error);
        if (exMessage != null) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage((errorMSG != null && errorMSG ? FacesMessage.SEVERITY_ERROR : FacesMessage.SEVERITY_INFO), exMessage, null));
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(MESSAGE, null);
        }
    }

    public static void setAjaxInfoMessage(String exMessage) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, exMessage, null));

    }

    public static void setAjaxErrorMessage(String exMessage) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, exMessage, null));
    }

    public static String getMessage(String key, String... param) {
        ResourceBundle bundle = ResourceBundle.getBundle("langue.message", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        String text = bundle.getString(key);             
        return MessageFormat.format(text, param);
    }
    
}
