/*
 * 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;

import org.apache.myfaces.orchestra.requestParameterProvider.RequestParameterProvider;

/**
 * Adds the required fields (conversationContext) to the request parameters.
 * <p>
 * This ensures that every URL in the generated page contains the current
 * conversation context id as a query parameter. When the request is submitted to the
 * server this query parameter is then used to select the correct ConversationContext
 * instance from the user session (ie the set of Conversation objects that are associated
 * with this particular window).
 */
public class ConversationRequestParameterProvider implements RequestParameterProvider
{
    private final static String[] NO_PARAMETERS = new String[0];

    private final static String[] REQUEST_PARAMETERS = new String[]
        {
            ConversationManager.CONVERSATION_CONTEXT_PARAM
        };

    private final static ThreadLocal inSeparationModeThreadLocal = new ThreadLocal();

    /**
     * Update a threadlocal flag indicating whether URLs written to the
     * response page should have the special ConversationContext query
     * parameter added to them or not.
     * <p>
     * Defaults to false (no separation), which means that urls ARE modified.
     * <p>
     * This can be called by a component before rendering its children in order to
     * skip this url mangling. Any code that calls this method is responsible for
     * restoring the original value at the appropriate time. This is very important,
     * because this is a thread-local value that will be inherited by whatever
     * request this pooled thread is reused for!
     */
    public static void setInSeparationMode(boolean separationMode)
    {
        // TODO: consider using a request-scope variable rather than a
        // ThreadLocal; less damage if the flag is not reset..
        inSeparationModeThreadLocal.set(separationMode ? Boolean.TRUE : Boolean.FALSE);
    }

    /**
     * Returns true if URLs should be written out unmodified, false if they should
     * have the conversation context id appended as a query parameter.
     */
    public static boolean isInSeparationMode()
    {
        return Boolean.TRUE.equals(inSeparationModeThreadLocal.get());
    }

    public String getFieldValue(String field)
    {
        if (isInSeparationMode())
        {
            return null;
        }

        ConversationManager conversationManager = ConversationManager.getInstance();
        if (conversationManager == null)
        {
            throw new IllegalStateException("can find the conversationManager");
        }

        // fetch the conversation context, creating one if it does not yet exist.
        ConversationContext ctx = conversationManager.getOrCreateCurrentConversationContext();
        return Long.toString(ctx.getId(), Character.MAX_RADIX);
    }

    //TODO: theoretical security problem here as something can call this method then
    // modify the 0th element of the returned array. If this library is deployed at the
    // "shared" level, that means that one webapp can cause a "denial of service" or
    // similar against other webapps in the container by changing this critical field.
    // Not a very important flaw, but nevertheless...
    public String[] getFields()
    {
        if (isInSeparationMode())
        {
            return NO_PARAMETERS;
        }

        return REQUEST_PARAMETERS;
    }
}
