/*
 * 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 com.facebook.presto.operator.window;

import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.aggregation.Accumulator;
import com.facebook.presto.operator.aggregation.AccumulatorFactory;
import com.facebook.presto.operator.aggregation.InternalAggregationFunction;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

public class AggregateWindowFunction
        implements WindowFunction
{
    private final InternalAggregationFunction function;
    private final List<Integer> argumentChannels;
    private final AccumulatorFactory accumulatorFactory;

    private WindowIndex windowIndex;

    private AggregateWindowFunction(InternalAggregationFunction function, List<Integer> argumentChannels)
    {
        this.function = checkNotNull(function, "function is null");
        this.argumentChannels = ImmutableList.copyOf(argumentChannels);
        this.accumulatorFactory = function.bind(createArgs(function), Optional.<Integer>absent(), Optional.<Integer>absent(), 1.0);
    }

    @Override
    public Type getType()
    {
        return function.getFinalType();
    }

    @Override
    public void reset(WindowIndex windowIndex)
    {
        this.windowIndex = windowIndex;
    }

    @Override
    public void processRow(BlockBuilder output, int peerGroupStart, int peerGroupEnd, int frameStart, int frameEnd)
    {
        PageBuilder pageBuilder = new PageBuilder(function.getParameterTypes());
        for (int position = frameStart; (position >= 0) && (position <= frameEnd); position++) {
            for (int i = 0; i < function.getParameterTypes().size(); i++) {
                windowIndex.appendTo(argumentChannels.get(i), position, pageBuilder.getBlockBuilder(i));
            }
            pageBuilder.declarePosition();
        }

        Accumulator accumulator = accumulatorFactory.createAccumulator();
        accumulator.addInput(pageBuilder.build());
        accumulator.evaluateFinal(output);
    }

    public static WindowFunctionSupplier supplier(Signature signature, final InternalAggregationFunction function)
    {
        checkNotNull(function, "function is null");
        return new AbstractWindowFunctionSupplier(signature, null)
        {
            @Override
            protected WindowFunction newWindowFunction(List<Integer> inputs)
            {
                return new AggregateWindowFunction(function, inputs);
            }
        };
    }

    private static List<Integer> createArgs(InternalAggregationFunction function)
    {
        ImmutableList.Builder<Integer> list = ImmutableList.builder();
        for (int i = 0; i < function.getParameterTypes().size(); i++) {
            list.add(i);
        }
        return list.build();
    }
}

@@ -1074,24 +1074,66 @@
 mutableList;
+%0Aimport com.google.common.primitives.Ints;
 %0A%0Aimport jav
@@ -1359,29 +1359,21 @@
 e final 
-List%3CInteger%3E
+int%5B%5D
  argumen
@@ -1477,16 +1477,111 @@
 owIndex;
+%0A    private Accumulator accumulator;%0A    private int currentStart;%0A    private int currentEnd;
 %0A%0A    pr
@@ -1791,27 +1791,19 @@
  = I
-mmutableList.copyOf
+nts.toArray
 (arg
@@ -2153,24 +2153,52 @@
 indowIndex;%0A
+        resetAccumulator();%0A
     %7D%0A%0A    @
@@ -2320,32 +2320,732 @@
 frameEnd)%0A    %7B%0A
+        if (frameStart %3C 0) %7B%0A            // empty frame%0A            resetAccumulator();%0A        %7D%0A        else if ((frameStart == currentStart) && (frameEnd %3E= currentEnd)) %7B%0A            // same or expanding frame%0A            accumulate(currentEnd + 1, frameEnd);%0A            currentEnd = frameEnd;%0A        %7D%0A        else %7B%0A            // different frame%0A            resetAccumulator();%0A            accumulate(frameStart, frameEnd);%0A            currentStart = frameStart;%0A            currentEnd = frameEnd;%0A        %7D%0A%0A        accumulator.evaluateFinal(output);%0A    %7D%0A%0A    private void accumulate(int start, int end)%0A    %7B%0A        // TODO: add Accumulator method that does not require creating pages%0A
         PageBuil
@@ -3141,40 +3141,15 @@
 n = 
-frameStart; (position %3E= 0) && (
+start; 
 posi
@@ -3156,25 +3156,19 @@
 tion %3C= 
-frameE
+e
 nd
-)
 ; positi
@@ -3308,15 +3308,11 @@
 nels
-.get(i)
+%5Bi%5D
 , po
@@ -3423,176 +3423,276 @@
   %7D%0A
+        accumulator.addInput(pageBuilder.build());
 %0A    
+%7D%0A%0A
     
-Accumulator accumulator = accumulatorFactory.createAccumulator();%0A        accumulator.addInput(pageBuilder.build());%0A        accumulator.evaluateFinal(output);
+private void resetAccumulator()%0A    %7B%0A        if (currentStart %3E= 0) %7B%0A            accumulator = accumulatorFactory.createAccumulator();%0A            currentStart = -1;%0A            currentEnd = -1;%0A        %7D
 %0A   

Optimize windowed aggregations