/*
 * 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 java.util.HashSet;
import java.util.Set;

import org.apache.myfaces.orchestra.frameworkAdapter.FrameworkAdapter;

/**
 * Manager to deal with page scoped beans.
 * <p>
 * Instances of this type are expected to be request-scoped, ie a new instance is used for
 * each request. The AccessScopeManagerConfiguration object that it references can be
 * of application scope.
 * 
 * @since 1.1
 */
public class AccessScopeManager
{
    private static final String REQ_ATTR_KEY = AccessScopeManager.class.getName();
    private AccessScopeManagerConfiguration accessScopeManagerConfiguration;

    private boolean recordAccess;
    private boolean ignoreRequest;
    private Set accessedConversations = new HashSet();

    public static AccessScopeManager getInstance()
    {
        // Get the instance by looking up a variable whose name is this class name, using the normal
        // managed bean lookup process. When an IOC framework like Spring is being used to extend
        // the standard JSF managed bean declaration facilities, then the bean may be retrieved
        // from there.
        //
        // Using a lookup of a managed bean allows the user to set configuration properties on the
        // manager class and its properties.

        FrameworkAdapter fa = FrameworkAdapter.getCurrentInstance();
        AccessScopeManager manager = (AccessScopeManager) fa.getRequestAttribute(REQ_ATTR_KEY);
        if (manager != null)
        {
            // already found and cached in request attributes
            return manager;
        }

        // Backwards compatibility hack: look for FlashScopeManager. It is possible that
        // a user of Orchestra 1.0 has copied the declaration from the original Orchestra
        // config file into their own code to inject special settings.
        manager = (AccessScopeManager) fa.getBean(FlashScopeManager.class.getName());
        if (manager != null)
        {
            fa.setRequestAttribute(REQ_ATTR_KEY, manager);
            return manager;
        }
        
        // Backwards compatibility hack: look for FlashScopeManagerConfiguration. It is
        // possible that a user of Orchestra 1.0 has overridden just the Configuration
        // bit to set their own ignoredViewId values (as recommended!):
        //
        // This is a little dodgy as settings made through the new AccessScopeManage
        // bean will will now be silently ignored.
        FlashScopeManagerConfiguration cfg = (FlashScopeManagerConfiguration) fa.getBean(
                FlashScopeManagerConfiguration.class.getName());
        if (cfg != null)
        {
            manager = new AccessScopeManager();
            manager.setAccessScopeManagerConfiguration(cfg);
            fa.setRequestAttribute(REQ_ATTR_KEY, manager);
            return manager;
        }
        
        // normal case
        manager = (AccessScopeManager) fa.getBean(AccessScopeManager.class.getName());
        if (manager != null)
        {
            fa.setRequestAttribute(REQ_ATTR_KEY, manager);
            return manager;
        }

        // TODO: Make this error message less spring-specific. Spring is not the only IOC container
        // that Orchestra can be used with.
        throw new IllegalArgumentException(
            "Orchestra was unable to create an instance of bean with name 'AccessScopeManager'." +
            " Ensure that JSF variable resolution uses your dependency injection (DI) framework" +
            " (eg Spring's DelegatingVariableResolver is in your faces-config.xml file) and" +
            " the standard Orchestra configuration beans are defined (eg by using"+
            " <import resource=\"classpath*:/META-INF/spring-orchestra-init.xml\" />)."); 
    }

    public AccessScopeManagerConfiguration getAccessScopeManagerConfiguration()
    {
        return accessScopeManagerConfiguration;
    }

    public void setAccessScopeManagerConfiguration(AccessScopeManagerConfiguration accessScopeManagerConfiguration)
    {
        this.accessScopeManagerConfiguration = accessScopeManagerConfiguration;
    }

    /**
     * This is invoked at the point in the request lifecycle after which we want to
     * start tracking use of access-scoped objects.
     */
    public void beginRecording() 
    {
        recordAccess = true;
    }

    /**
     * Add a conversation to the list of accessed conversations.
     * <p>
     * This method is expected to be called via AOP proxies wrapped around each conversation-scoped
     * bean; any invocation of a method on such a bean causes the conversation associated with that
     * bean to be added to the accessed list here.
     */
    public void addConversationAccess(String conversationName)
    {
        // Don't bother tracking accessed conversations if we will never use the data.
        // Otherwise, add this conversation name to the list of accessed conversations.
        if (recordAccess && !ignoreRequest && !accessedConversations.contains(conversationName))
        {
            accessedConversations.add(conversationName);
        }
    }

    public boolean isIgnoreRequest()
    {
        return ignoreRequest;
    }

    /**
     * Suppress access scope for the current request, ie do not terminate conversations that are
     * not accessed by this request.
     * <p>
     * This can come in useful occasionally, particularly when handling AJAX requests which
     * only access some of the beans associated with the current view.
     */
    public void setIgnoreRequest()
    {
        this.ignoreRequest = true;
    }

    public boolean isConversationAccessed(String name)
    {
        if (ignoreRequest)
        {
            throw new IllegalStateException();
        }

        return accessedConversations.contains(name);
    }
}
