/*
 * @(#)AbstractMultipleStore.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.util.classes.v1;


import java.util.Vector;
import java.util.Enumeration;

import org.apache.log4j.Logger;


/**
 * Similar in concept to the <tt>AbstractSingleStore</tt>, except this houses
 * multiple instances of 'singletons'.
 *
 * @author  Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version $Date: 2003/02/10 22:52:36 $
 * @since   June 28, 2002
 */
public abstract class AbstractMultipleStore
{
    private static final Logger LOG = Logger.getLogger(
        AbstractMultipleStore.class.getName() );

    private Class instanceOf;
    private Vector store = new Vector();
    private AllowMultiplesAction action;

    /**
     * It stores each class already stored.
     * This should in reality be a HashSet, but Hashtable may be a bit too
     * much for our purposes.
     */
    private Vector usedClasses = new Vector();
    
    
    public static abstract class AllowMultiplesAction
    {
        // don't allow outside replacements
        AllowMultiplesAction() {}
        protected abstract boolean addedMultiple( Object singleton,
                Class baseClass );
        public abstract String toString();
    }
    
    
    public static final AllowMultiplesAction NO_MULTIPLES_ERROR =
        new AllowMultiplesAction() {
            protected boolean addedMultiple(Object singleton, Class baseClass)
            {
                throw new IllegalArgumentException( "Passed-in singleton "+
                    singleton+" has class "+baseClass.getName()+
                    " which has already been added to the store" );
            }
            public String toString()
            {
                return "[No multiple entries with same class allowed "+
                    "without error]";
            }
        };
    
    
    public static final AllowMultiplesAction NO_MULTIPLES_SILENT =
        new AllowMultiplesAction() {
            protected boolean addedMultiple(Object singleton, Class baseClass)
            {
                // don't allow it
                return false;
            }
            public String toString()
            {
                return "[No multiple entries with same class allowed]";
            }
        };
    
    
    public static final AllowMultiplesAction MULTIPLES_OK =
        new AllowMultiplesAction() {
            protected boolean addedMultiple(Object singleton, Class baseClass)
            {
                // allow it
                return true;
            }
            public String toString()
            {
                return "[Multiple entries with same class allowed]";
            }
        };
    
    
    /**
     * Constructor specifying all the parameters for using a singleton in this
     * framework.
     *
     * @param instanceOf singletons must be of this class.
     * @param ama <tt>true</tt> if this store should allow
     *      multiple instances of the exact same class, or <tt>false</tt>
     *      if it should prevent multiple instances sharing the exact
     *      same class.  This helps to enforce the idea of 'singleton'.
     */
    public AbstractMultipleStore( Class instanceOf, AllowMultiplesAction ama )
    {
        this.instanceOf = instanceOf;
        this.usedClasses = new Vector();
        this.action = ama;
    }
    
    
    /**
     * Returns the current inner singletons.  If it has never been set, then
     * the default will be used instead.
     *
     * @return the inner singleton instances.
     * @exception IllegalStateException if no singleton was created.
     */
    public Enumeration getSingletons()
    {
        Enumeration enum;
        synchronized( this )
        {
            if (this.store.size() <= 0)
            {
                addDefaultSingletons();
                if (this.store.size() <= 0)
                {
                    LOG.warn( "No singleton created." );
                }
            }
            enum = this.store.elements();
        }
        return enum;
    }
    
    
    /**
     * Sets the singleton.  It must be of the correct class, and non-null.
     *
     * @param singleton the singleton to set.
     * @exception IllegalArgumentException if <tt>singleton</tt> is
     *      <tt>null</tt>, or is not of the correct type.
     */
    public synchronized void addSingleton( Object singleton )
    {
        if (singleton == null)
        {
            throw new IllegalArgumentException("no null arguments");
        }
        if (this.instanceOf != null &&
            !this.instanceOf.isInstance( singleton ))
        {
            throw new IllegalArgumentException( "Passed-in singleton "+
                singleton+" is not assignable to class "+
                this.instanceOf.getName()+", but is of class "+
                singleton.getClass().getName() );
        }
        Class c = singleton.getClass();
        
        // optimization of following logic:
        /*
        if (!this.usedClasses.contains( c )
            || this.action.addedMultiple( singleton, this.instanceOf ))
        {
            this.store.addElement( singleton );
            this.usedClasses.addElement( c );
        }
        */
        if (this.usedClasses.contains( c ))
        {
            if (this.action.addedMultiple( singleton, this.instanceOf ))
            {
                this.store.addElement( singleton );
            }
        }
        else
        {
            this.store.addElement( singleton );
            this.usedClasses.addElement( c );
        }
    }
    
    
    /**
     * Adds the default inner singletons, which is an implementation
     * specific method.
     */
    protected abstract void addDefaultSingletons();
}

