/*
 * 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 io.prestosql.operator.scalar;

import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.prestosql.metadata.FunctionArgumentDefinition;
import io.prestosql.metadata.FunctionBinding;
import io.prestosql.metadata.FunctionMetadata;
import io.prestosql.metadata.Signature;
import io.prestosql.metadata.SqlScalarFunction;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.type.TypeSignature;

import java.lang.invoke.MethodHandle;

import static io.prestosql.metadata.FunctionKind.SCALAR;
import static io.prestosql.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.prestosql.spi.function.InvocationConvention.InvocationArgumentConvention.NEVER_NULL;
import static io.prestosql.spi.function.InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL;
import static io.prestosql.spi.type.VarbinaryType.VARBINARY;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.util.Reflection.methodHandle;
import static java.lang.Math.addExact;
import static java.util.Collections.nCopies;

public final class ConcatFunction
        extends SqlScalarFunction
{
    // TODO design new variadic functions binding mechanism that will allow to produce VARCHAR(x) where x < MAX_LENGTH.
    public static final ConcatFunction VARCHAR_CONCAT = new ConcatFunction(VARCHAR.getTypeSignature(), "Concatenates given strings");

    public static final ConcatFunction VARBINARY_CONCAT = new ConcatFunction(VARBINARY.getTypeSignature(), "concatenates given varbinary values");

    private ConcatFunction(TypeSignature type, String description)
    {
        super(new FunctionMetadata(
                new Signature(
                        "concat",
                        ImmutableList.of(),
                        ImmutableList.of(),
                        type,
                        ImmutableList.of(type),
                        true),
                false,
                ImmutableList.of(new FunctionArgumentDefinition(false)),
                false,
                true,
                description,
                SCALAR));
    }

    @Override
    protected ScalarFunctionImplementation specialize(FunctionBinding functionBinding)
    {
        int arity = functionBinding.getArity();

        if (arity < 2) {
            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "There must be two or more concatenation arguments");
        }

        if (arity > 254) {
            throw new PrestoException(NOT_SUPPORTED, "Too many arguments for string concatenation");
        }

        MethodHandle arrayMethodHandle = methodHandle(ConcatFunction.class, "concat", Slice[].class);
        MethodHandle customMethodHandle = arrayMethodHandle.asCollector(Slice[].class, arity);

        return new ChoicesScalarFunctionImplementation(
            functionBinding,
            FAIL_ON_NULL,
            nCopies(arity, NEVER_NULL),
            customMethodHandle);
    }

    public static Slice concat(Slice[] values)
    {
        // Validate the concatenation length
        int length = 0;
        for (Slice value : values) {
            length = checkedAdd(length, value.length());
        }

        // Construct the result
        Slice result = Slices.allocate(length);
        int position = 0;
        for (Slice value : values) {
            result.setBytes(position, value);
            position += value.length();
        }

        return result;
    }

    private static int checkedAdd(int x, int y)
    {
        try {
            return addExact(x, y);
        }
        catch (ArithmeticException e) {
            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Concatenated string is too large");
        }
    }
}

@@ -1265,16 +1265,103 @@
 PORTED;%0A
+import static io.prestosql.spi.block.PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES;%0A
 import s
@@ -1450,24 +1450,24 @@
 NEVER_NULL;%0A
-
 import stati
@@ -2285,24 +2285,159 @@
  values%22);%0A%0A
+    private static final int MAX_INPUT_VALUES = 254;%0A    private static final int MAX_OUTPUT_LENGTH = DEFAULT_MAX_PAGE_SIZE_IN_BYTES;%0A%0A
     private 
@@ -3329,19 +3329,32 @@
 arity %3E 
-254
+MAX_INPUT_VALUES
 ) %7B%0A    
@@ -4030,26 +4030,24 @@
 ength = 
-checkedAdd
+addExact
 (length,
@@ -4060,24 +4060,190 @@
 .length());%0A
+            if (length %3E MAX_OUTPUT_LENGTH) %7B%0A                throw new PrestoException(INVALID_FUNCTION_ARGUMENT, %22Concatenated string is too large%22);%0A            %7D%0A
         %7D%0A%0A 
@@ -4473,32 +4473,32 @@
 h();%0A        %7D%0A%0A
+
         return r
@@ -4513,279 +4513,7 @@
    %7D
-%0A%0A    private static int checkedAdd(int x, int y)%0A    %7B%0A        try %7B%0A            return addExact(x, y);%0A        %7D%0A        catch (ArithmeticException e) %7B%0A            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, %22Concatenated string is too large%22);%0A        %7D%0A    %7D
 %0A%7D%0A

Put stricter upper bound on Concat output