/*
 * 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;

import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockCursor;
import com.facebook.presto.operator.SetBuilderOperator.SetSupplier;
import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.List;

import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.util.MoreFutures.tryGetUnchecked;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

public class HashSemiJoinOperator
        implements Operator
{
    private final OperatorContext operatorContext;

    public static class HashSemiJoinOperatorFactory
            implements OperatorFactory
    {
        private final int operatorId;
        private final SetSupplier setSupplier;
        private final List<Type> probeTypes;
        private final int probeJoinChannel;
        private final List<Type> types;
        private boolean closed;

        public HashSemiJoinOperatorFactory(int operatorId, SetSupplier setSupplier, List<? extends Type> probeTypes, int probeJoinChannel)
        {
            this.operatorId = operatorId;
            this.setSupplier = setSupplier;
            this.probeTypes = ImmutableList.copyOf(probeTypes);
            checkArgument(probeJoinChannel >= 0, "probeJoinChannel is negative");
            this.probeJoinChannel = probeJoinChannel;

            this.types = ImmutableList.<Type>builder()
                    .addAll(probeTypes)
                    .add(BOOLEAN)
                    .build();
        }

        @Override
        public List<Type> getTypes()
        {
            return types;
        }

        @Override
        public Operator createOperator(DriverContext driverContext)
        {
            checkState(!closed, "Factory is already closed");
            OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, HashBuilderOperator.class.getSimpleName());
            return new HashSemiJoinOperator(operatorContext, setSupplier, probeTypes, probeJoinChannel);
        }

        @Override
        public void close()
        {
            closed = true;
        }
    }

    private final int probeJoinChannel;
    private final List<Type> types;
    private final ListenableFuture<ChannelSet> channelSetFuture;

    private ChannelSet channelSet;
    private Page outputPage;
    private boolean finishing;

    public HashSemiJoinOperator(OperatorContext operatorContext, SetSupplier channelSetFuture, List<Type> probeTypes, int probeJoinChannel)
    {
        this.operatorContext = checkNotNull(operatorContext, "operatorContext is null");

        // todo pass in desired projection
        checkNotNull(channelSetFuture, "hashProvider is null");
        checkNotNull(probeTypes, "probeTypes is null");
        checkArgument(probeJoinChannel >= 0, "probeJoinChannel is negative");

        this.channelSetFuture = channelSetFuture.getChannelSet();
        this.probeJoinChannel = probeJoinChannel;

        this.types = ImmutableList.<Type>builder()
                .addAll(probeTypes)
                .add(BOOLEAN)
                .build();
    }

    @Override
    public OperatorContext getOperatorContext()
    {
        return operatorContext;
    }

    @Override
    public List<Type> getTypes()
    {
        return types;
    }

    @Override
    public void finish()
    {
        finishing = true;
    }

    @Override
    public boolean isFinished()
    {
        return finishing && outputPage == null;
    }

    @Override
    public ListenableFuture<?> isBlocked()
    {
        return channelSetFuture;
    }

    @Override
    public boolean needsInput()
    {
        if (finishing || outputPage != null) {
            return false;
        }

        if (channelSet == null) {
            channelSet = tryGetUnchecked(channelSetFuture);
        }
        return channelSet != null;
    }

    @Override
    public void addInput(Page page)
    {
        checkNotNull(page, "page is null");
        checkState(!finishing, "Operator is finishing");
        checkState(channelSet != null, "Set has not been built yet");
        checkState(outputPage == null, "Operator still has pending output");

        // create the block builder for the new boolean column
        // we know the exact size required for the block
        BlockBuilder blockBuilder = BOOLEAN.createFixedSizeBlockBuilder(page.getPositionCount());

        Block probeJoinBlock = page.getBlock(probeJoinChannel);
        BlockCursor probeJoinCursor = probeJoinBlock.cursor();

        // update hashing strategy to use probe cursor
        for (int position = 0; position < page.getPositionCount(); position++) {
            checkState(probeJoinCursor.advanceNextPosition());
            if (probeJoinCursor.isNull()) {
                blockBuilder.appendNull();
            }
            else {
                boolean contains = channelSet.contains(position, probeJoinBlock);
                if (!contains && channelSet.containsNull()) {
                    blockBuilder.appendNull();
                }
                else {
                    blockBuilder.appendBoolean(contains);
                }
            }
        }

        // add the new boolean column to the page
        Block[] sourceBlocks = page.getBlocks();
        Block[] outputBlocks = new Block[sourceBlocks.length + 1]; // +1 for the single boolean output channel

        System.arraycopy(sourceBlocks, 0, outputBlocks, 0, sourceBlocks.length);
        outputBlocks[sourceBlocks.length] = blockBuilder.build();

        outputPage = new Page(outputBlocks);
    }

    @Override
    public Page getOutput()
    {
        Page result = outputPage;
        outputPage = null;
        return result;
    }
}

@@ -621,31 +621,55 @@
 .presto.
-spi.block.Block
+operator.SetBuilderOperator.SetSupplier
 ;%0Aimport
@@ -704,23 +704,16 @@
 ck.Block
-Builder
 ;%0Aimport
@@ -752,80 +752,13 @@
 lock
-Cursor;%0Aimport com.facebook.presto.operator.SetBuilderOperator.SetSuppli
+Build
 er;%0A
@@ -5268,71 +5268,8 @@
 el);
-%0A        BlockCursor probeJoinCursor = probeJoinBlock.cursor();
 %0A%0A  
@@ -5406,71 +5406,8 @@
 ) %7B%0A
-            checkState(probeJoinCursor.advanceNextPosition());%0A
     
@@ -5431,22 +5431,21 @@
 Join
-Cursor
+Block
 .isNull(
 )) %7B
@@ -5436,24 +5436,32 @@
 lock.isNull(
+position
 )) %7B%0A       

Change semi join to not use BlockCursor