/*
 * Copyright (c) 2008, Rickard Öberg. All Rights Reserved.
 *
 * Licensed 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.qi4j.runtime.composite;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.qi4j.runtime.object.ObjectBuilderInstance;

/**
 * JAVADOC
 */
public final class UsesInstance
{
    public static final UsesInstance NO_USES = new UsesInstance();

    private final Set<Object> uses = new HashSet<Object>();

    public void use( Object... objects )
    {
        uses.addAll( Arrays.asList( objects ) );
    }

    public Object useForType( Class<?> type )
    {
        for( Object use : uses )
        {
            if( use instanceof CompositeBuilderInstance )
            {
                CompositeBuilderInstance builder = (CompositeBuilderInstance) use;
                if( type.isAssignableFrom( builder.compositeType() ) )
                {
                    return builder.newInstance();
                }
            } else if( use instanceof ObjectBuilderInstance )
            {
                ObjectBuilderInstance builder = (ObjectBuilderInstance) use;
                if( type.isAssignableFrom( builder.objectType() ) )
                {
                    return builder.newInstance();
                }
            }

            if( type.isInstance( use ) )
            {
                return use;
            }
        }

        return null;
    }
}

@@ -1102,32 +1102,242 @@
 ?%3E type )%0A    %7B%0A
+        // Check instances first%0A        for( Object use : uses )%0A        %7B%0A            if( type.isInstance( use ) )%0A            %7B%0A                return use;%0A            %7D%0A        %7D%0A%0A        // Check builders%0A
         for( Obj
@@ -1999,106 +1999,8 @@
    %7D
-%0A%0A            if( type.isInstance( use ) )%0A            %7B%0A                return use;%0A            %7D
 %0A   

Allow injection of Iterable<Foo> with @Uses, to get new instances every time.