/*
 * 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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.myfaces.orchestra.conversation.basic.LogConversationMessager;
import org.apache.myfaces.orchestra.frameworkAdapter.FrameworkAdapter;
import org.apache.myfaces.orchestra.frameworkAdapter.local.LocalFrameworkAdapter;

/**
 * The ConversationWiperThread will trigger the conversation timeout check.
 * <p>
 * This is typically started from a servlet session listener when the webapp starts.
 * 
 * @see org.apache.myfaces.orchestra.conversation.servlet.ConversationManagerSessionListener
 */
public class ConversationWiperThread extends Thread
{
    private final Log log = LogFactory.getLog(ConversationWiperThread.class);

    private final long checkTime;

    private Set conversationManagers = new HashSet();

    /**
     * Constructor.
     * 
     * @param checkTime is interval in milliseconds between scans of the existing
     * ConversationManagers to look for timeouts.
     */
    public ConversationWiperThread(long checkTime)
    {
        this.checkTime = checkTime;

        setDaemon(true);
        setName(ConversationWiperThread.class.getName());
    }

    /**
     * Add a ConversationManager to check.
     * 
     * @since 1.1
     */
    public void addConversationManager(ConversationManager cm)
    {
        synchronized (conversationManagers)
        {
            conversationManagers.add(cm);
        }
    }

    /**
     * Remove a ConversationManager from the list to check.
     * 
     * @since 1.1
     */
    public void removeConversationManager(ConversationManager cm)
    {
        synchronized (conversationManagers)
        {
            boolean found = conversationManagers.remove(cm);
            if (!found)
            {
                // sanity check: this should not happen.
                log.error("Conversation Manager not found in remove");
            }
        }
    }

    public void run()
    {
        log.debug("ConversationWiperThread startup"); // NON-NLS
        _run();
        log.debug("ConversationWiperThread shtudown"); // NON-NLS
    }

    private void _run()
    {
        // Set up a custom FrameworkAdapter for this thread, so other orchestra code used by this
        // thread which expects one to exist will not throw NullPointerException.
        FrameworkAdapter fa = new LocalFrameworkAdapter();
        ConversationMessager conversationMessager = new LogConversationMessager();
        fa.setConversationMessager(conversationMessager);
        FrameworkAdapter.setCurrentInstance(fa);

        while (!isInterrupted())
        {
            ConversationManager[] managersArray;
            synchronized (conversationManagers)
            {
                managersArray = new ConversationManager[conversationManagers.size()];
                conversationManagers.toArray(managersArray);
            }

            if (log.isDebugEnabled())
            {
                log.debug("ConversationWiperThread running against " + managersArray.length + " instances.");
            }

            for (int i = 0; i<managersArray.length; i++)
            {
                ConversationManager conversationManager = managersArray[i];
                conversationManager.checkTimeouts();
            }

            try
            {
                Thread.sleep(checkTime);
            }
            catch (InterruptedException e)
            {
                return;
            }
        }
    }
}
