/*
 *  Copyright 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 therian.operator.add;

import java.lang.reflect.Type;
import java.util.Collection;

import org.apache.commons.lang3.reflect.TypeUtils;

import therian.TherianContext;
import therian.buildweaver.StandardOperator;
import therian.operation.Add;
import therian.operation.ImmutableCheck;
import therian.util.Types;

/**
 * Add an element to a {@link Collection}.
 */
@StandardOperator
public class AddToCollection implements therian.Operator<Add<?, Collection<?>>> {

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public boolean perform(TherianContext context, Add<?, Collection<?>> operation) {
        ((Collection) operation.getTargetPosition().getValue()).add(operation.getSourcePosition().getValue());
        operation.setResult(Boolean.TRUE);
        return true;
    }

    @Override
    public boolean supports(TherianContext context, Add<?, Collection<?>> operation) {
        // cannot add to immutable types
        if (context.eval(ImmutableCheck.of(operation.getTargetPosition())).booleanValue()) {
            return false;
        }
        if (!TypeUtils.isAssignable(operation.getTargetPosition().getType(), Collection.class)) {
            return false;
        }
        final Type targetElementType =
                Types.unrollVariables(
                    TypeUtils.getTypeArguments(operation.getTargetPosition().getType(), Collection.class),
                    Collection.class.getTypeParameters()[0]);

        if (targetElementType == null) {
            // raw collection
            return true;
        }
        return TypeUtils.isAssignable(operation.getSourcePosition().getType(), targetElementType);
    }

}

@@ -1227,32 +1227,67 @@
 %3E%3E operation) %7B%0A
+        final boolean result =%0A    
         ((Collec
@@ -1413,20 +1413,14 @@
 ult(
-Boolean.TRUE
+result
 );%0A 
@@ -1898,28 +1898,24 @@
             
-    
 Types.unroll
@@ -1925,20 +1925,16 @@
 iables(%0A
-    
         
@@ -2028,20 +2028,16 @@
 class),%0A
-    
         

improve results; format