/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.myfaces.orchestra.conversation.jsf;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.myfaces.orchestra.conversation.ConversationMessager;

/**
 * Inform the user about some anomalies by displaying the problems as standard JSF messages.
 * <p>
 * This class just provides some default behaviour; if you don't like it then implement your
 * own version of this class and configure your alternative as the standard "Conversation Messager"
 * instead. See the documentation on interface ConversationMessager for details.
 * <p>
 * As required by the ConversationMessager interface, all methods on this class are thread-safe.
 */
public class JsfConversationMessager extends ConversationMessager
{
    public void setConversationException(Throwable t)
    {
        String msgSummary = t.getLocalizedMessage();
        String msgDetail = getThrowableText(t);
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_FATAL, msgSummary, msgDetail);
        FacesContext.getCurrentInstance().addMessage(null, msg); 
    }

    public void setConversationNotActive(String name)
    {
        String msgSummary = "Conversation not active";
        String msgDetail = "Conversation not active. Please start over. (Conversation Name:" + name + ")";
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_FATAL, msgSummary, msgDetail);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    protected String getThrowableText(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        return sw.toString();
    }
}
