/*
 * Copyright 2014 the original author or authors.
 *
 * 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.gradle.model.internal.inspect;

import org.gradle.internal.BiAction;
import org.gradle.model.internal.core.*;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.manage.instance.ManagedProxyFactory;
import org.gradle.model.internal.manage.instance.ModelInstantiator;
import org.gradle.model.internal.manage.schema.ModelProperty;
import org.gradle.model.internal.manage.schema.ModelSchema;
import org.gradle.model.internal.manage.schema.ModelSchemaStore;
import org.gradle.model.internal.type.ModelType;

import java.util.List;

public class ManagedModelInitializer<T> implements BiAction<MutableModelNode, Inputs> {
    private static final BiAction<MutableModelNode, Inputs> NO_OP = new BiAction<MutableModelNode, Inputs>() {
        @Override
        public void execute(MutableModelNode mutableModelNode, Inputs inputs) {
        }
    };

    private final ModelSchema<T> modelSchema;
    private final BiAction<? super MutableModelNode, ? super Inputs> initializer;
    private final ManagedProxyFactory proxyFactory;
    private final ModelSchemaStore schemaStore;
    private final ModelInstantiator modelInstantiator;
    private final ModelRuleDescriptor descriptor;

    public static <T> ModelCreator creator(ModelRuleDescriptor descriptor, ModelPath path, ModelSchema<T> schema, ModelSchemaStore schemaStore, ModelInstantiator modelInstantiator, ManagedProxyFactory proxyFactory, List<? extends ModelReference<?>> inputs, BiAction<? super MutableModelNode, ? super Inputs> initializer) {
        return ModelCreators.of(ModelReference.of(path, schema.getType()), new ManagedModelInitializer<T>(descriptor, schema, modelInstantiator, schemaStore, proxyFactory, initializer))
                .descriptor(descriptor)
                .withProjection(new ManagedModelProjection<T>(schema.getType(), schemaStore, proxyFactory))
                .inputs(inputs)
                .build();
    }

    public ManagedModelInitializer(ModelRuleDescriptor descriptor, ModelSchema<T> modelSchema, ModelInstantiator modelInstantiator, ModelSchemaStore schemaStore, ManagedProxyFactory proxyFactory, BiAction<? super MutableModelNode, ? super Inputs> initializer) {
        this.descriptor = descriptor;
        this.modelInstantiator = modelInstantiator;
        this.schemaStore = schemaStore;
        this.modelSchema = modelSchema;
        this.initializer = initializer;
        this.proxyFactory = proxyFactory;
    }

    public void execute(MutableModelNode modelNode, Inputs inputs) {
        for (ModelProperty<?> property : modelSchema.getProperties().values()) {
            addPropertyLink(modelNode, property);
        }

        initializer.execute(modelNode, inputs);
    }

    private <P> void addPropertyLink(MutableModelNode modelNode, ModelProperty<P> property) {
        // TODO reuse pooled projections
        ModelType<P> propertyType = property.getType();
        ModelSchema<P> propertySchema = schemaStore.getSchema(propertyType);

        MutableModelNode childNode;

        if (propertySchema.getKind() == ModelSchema.Kind.STRUCT && !property.isWritable()) {
            ModelProjection projection = new ManagedModelProjection<P>(propertyType, schemaStore, proxyFactory);
            ModelCreator creator = ModelCreators.of(ModelReference.of(modelNode.getPath().child(property.getName()), propertyType), NO_OP)
                    .withProjection(projection)
                    .descriptor(descriptor).build();
            childNode = modelNode.addLink(creator);
            // TODO - defer creation
            childNode.ensureCreated();

            for (ModelProperty<?> modelProperty : propertySchema.getProperties().values()) {
                addPropertyLink(childNode, modelProperty);
            }
        } else {
            ModelProjection projection = new UnmanagedModelProjection<P>(propertyType, true, true);
            ModelCreator creator = ModelCreators.of(ModelReference.of(modelNode.getPath().child(property.getName()), propertyType), NO_OP)
                    .withProjection(projection)
                    .descriptor(descriptor).build();
            childNode = modelNode.addLink(creator);
            // TODO - defer creation
            childNode.ensureCreated();

            if (propertySchema.getKind() == ModelSchema.Kind.COLLECTION) {
                P instance = modelInstantiator.newInstance(propertySchema);
                childNode.setPrivateData(propertyType, instance);
            }
        }
    }
}

@@ -4423,16 +4423,77 @@
   %7D else
+ if (propertySchema.getKind() == ModelSchema.Kind.COLLECTION)
  %7B%0A     
@@ -4532,21 +4532,18 @@
 n = 
-new Unm
+M
 anaged
+Set
 Mode
@@ -4545,35 +4545,35 @@
 tModelProjection
-%3CP%3E
+.of
 (propertyType, t
@@ -4573,20 +4573,34 @@
 Type
-, true, true
+.getTypeVariables().get(0)
 );%0A 
@@ -4983,188 +4983,364 @@
     
-if (propertySchema.getKind() == ModelSchema.Kind.COLLECTION) %7B%0A                P instance = modelInstantiator.newInstance(propertySchema);%0A                child
+P instance = modelInstantiator.newInstance(propertySchema);%0A            childNode.setPrivateData(propertyType, instance);%0A        %7D else %7B%0A            ModelProjection projection = new UnmanagedModelProjection%3CP%3E(propertyType, true, true);%0A            ModelCreator creator = ModelCreators.of(ModelReference.of(model
 Node.
-setPrivateData(
+getPath().child(property.getName()), 
 prop
@@ -5351,34 +5351,246 @@
 Type
+)
 , 
-instance);%0A            %7D
+NO_OP)%0A                    .withProjection(projection)%0A                    .descriptor(descriptor).build();%0A            childNode = modelNode.addLink(creator);%0A            // TODO - defer creation%0A            childNode.ensureCreated();
 %0A   

Use a ManagedSetModelProjection for properties of type ManagedSet on nested managed types.