/*
 * Licensed to Crate under one or more contributor license agreements.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.  Crate licenses this file
 * to you 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.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial
 * agreement.
 */

package io.crate.operation.collect;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import io.crate.analyze.WhereClause;
import io.crate.analyze.symbol.Symbol;
import io.crate.core.collections.Row;
import io.crate.integrationtests.SQLHttpIntegrationTest;
import io.crate.metadata.Routing;
import io.crate.metadata.RowGranularity;
import io.crate.planner.distribution.DistributionInfo;
import io.crate.planner.node.dql.RoutedCollectPhase;
import io.crate.planner.projection.Projection;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.hamcrest.Matchers.is;

@ESIntegTestCase.ClusterScope(numDataNodes = 1)
public class ShardCollectServiceTest extends SQLHttpIntegrationTest {

    @Test
    public void testReadIsolation() throws Exception {
        execute("create blob table b1 clustered into 1 shards with (number_of_replicas = 0)");
        ensureGreen();
        upload("b1", "foo");
        upload("b1", "bar");

        Injector injector = internalCluster().getInstance(IndicesService.class).indexService(".blob_b1")
            .shardInjectorSafe(0);
        ShardCollectService shardCollectService = injector.getInstance(ShardCollectService.class);
        RoutedCollectPhase collectPhase = new RoutedCollectPhase(
            UUID.randomUUID(),
            1,
            "collect",
            new Routing(ImmutableMap.<String, Map<String, List<Integer>>>of()),
            RowGranularity.SHARD,
            ImmutableList.<Symbol>of(),
            ImmutableList.<Projection>of(),
            WhereClause.MATCH_ALL,
            DistributionInfo.DEFAULT_BROADCAST
        );

        // No read Isolation
        Iterable<Row> iterable = shardCollectService.getBlobRows(collectPhase, false);
        assertThat(Iterables.size(iterable), is(2));
        upload("b1", "newEntry1");
        assertThat(Iterables.size(iterable), is(3));

        // Read isolation
        iterable = shardCollectService.getBlobRows(collectPhase, true);
        assertThat(Iterables.size(iterable), is(3));
        upload("b1", "newEntry2");
        assertThat(Iterables.size(iterable), is(3));
    }
}

@@ -1618,16 +1618,61 @@
 jector;%0A
+import org.elasticsearch.index.IndexService;%0A
 import o
@@ -1939,16 +1939,36 @@
 odes = 1
+, numClientNodes = 0
 )%0Apublic
@@ -2032,16 +2032,70 @@
 Test %7B%0A%0A
+    private ShardCollectService shardCollectService;%0A%0A
     @Tes
@@ -2250,31 +2250,8 @@
 %22);%0A
-        ensureGreen();%0A
     
@@ -2304,25 +2304,24 @@
 %22bar%22);%0A
-%0A
         
 Injector
@@ -2316,148 +2316,32 @@
     
-Injector injector = internalCluster().getInstance(IndicesService.class).indexService(%22.blob_b1%22)%0A            .shardInjectorSafe(0
+ensureGreen(
 );%0A
+%0A
         
 Shar
@@ -2340,99 +2340,40 @@
     
-ShardCollectService shardCollectService = injector.getInstance(ShardCollectService.class
+assertBusy(new Initializer()
 );%0A
+%0A
     
@@ -3297,11 +3297,692 @@
 );%0A    %7D
+%0A%0A    private final class Initializer implements Runnable %7B%0A        @Override%0A        public void run() %7B%0A            try %7B%0A                IndexService indexService = internalCluster().getInstance(IndicesService.class).indexService(%22.blob_b1%22);%0A                assertNotNull(indexService);%0A                Injector injector = indexService.shardInjectorSafe(0);%0A                assertNotNull(injector);%0A                shardCollectService = injector.getInstance(ShardCollectService.class);%0A                assertNotNull(shardCollectService);%0A            %7D catch (Exception e) %7B%0A                fail(%22Exception shouldn't be thrown: %22 + e.getMessage());%0A            %7D%0A        %7D%0A    %7D
 %0A%7D%0A

Fix flaky test by using assertBusy to avoid NPE