/*
 * Licensed to CRATE Technology GmbH ("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.integrationtests;

import io.crate.Constants;
import io.crate.action.sql.SQLActionException;
import io.crate.test.integration.CrateIntegrationTest;
import org.elasticsearch.action.count.CountRequest;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.count.CrateTransportCountAction;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.hamcrest.core.Is.is;

@CrateIntegrationTest.ClusterScope(scope = CrateIntegrationTest.Scope.GLOBAL)
public class CountStarIntegrationTest extends SQLTransportIntegrationTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testCountWithPartitionFilter() throws Exception {
        execute("create table t (name string, p string) partitioned by (p) clustered into 2 shards " +
                "with (number_of_replicas = 0)");
        ensureGreen();

        execute("select count(*) from t");
        assertThat(response.rowCount(), is(1L));
        assertThat((Long) response.rows()[0][0], is(0L));

        execute("insert into t (name, p) values ('Arthur', 'foo')");
        execute("insert into t (name, p) values ('Trillian', 'foobar')");
        ensureGreen();
        refresh();

        execute("select count(*) from t where p = 'foobar'");
        assertThat(response.rowCount(), is(1L));
        assertThat((Long) response.rows()[0][0], is(1L));
    }

    @Test
    public void testCountRouting() throws Exception {
        execute("create table count_routing (" +
                  "street string, " +
                  "number short, " +
                  "zipcode string" +
                ") clustered by (zipcode) with (number_of_replicas=0)");
        ensureGreen();
        execute("insert into count_routing (street, number, zipcode) values " +
                "('Hintere Achmühler Str. 1', 8, '1,2'), " +
                "('Ritterstr.', 12, '1')," +
                "('Unknown Street', 69, '')");
        assertThat(response.rowCount(), is(3L));
        execute("refresh table count_routing");

        execute("select count(*) from count_routing where zipcode='1,2'");
        assertThat((Long)response.rows()[0][0], is(1L)); // FOUND ONLY ONE

        execute("select count(*) from count_routing where zipcode=''");
        assertThat((Long)response.rows()[0][0], is(1L)); // FOUND ONE

        CrateTransportCountAction action = cluster().getInstance(CrateTransportCountAction.class);
        CountResponse response1 = action.execute(
                new CountRequest("count_routing")
                        .types(Constants.DEFAULT_MAPPING_TYPE)
                        .routing("1,2")
        ).actionGet();
        assertThat(response1.getCount(), is(1L));

        CountResponse response2 = action.execute(
                new CountRequest("count_routing")
                        .types(Constants.DEFAULT_MAPPING_TYPE)
                        .routing("")
        ).actionGet();
        assertThat(response2.getCount(), is(1L));
    }

    @Test
    public void testSelectCountStarWithWhereClauseForUnknownCol() throws Exception {
        expectedException.expect(SQLActionException.class);
        expectedException.expectMessage("Column non_existant unknown");
        execute("create table test (\"name\" string) with (number_of_replicas=0)");
        execute("select count(*) from test where non_existant = 'Some Value'");
    }

        @Test
    public void testCountRoutingClusteredById() throws Exception {
        execute("create table auto_id (" +
                "  name string," +
                "  location geo_point" +
                ") with (number_of_replicas=0)");
        ensureGreen();

        execute("insert into auto_id (name, location) values (',', [36.567, 52.998]), ('Dornbirn', [54.45, 4.567])");
        execute("refresh table auto_id");

        execute("select count(*) from auto_id where _id=''");
        assertThat((Long)response.rows()[0][0], is(0L)); // FOUND NONE

        execute("select count(*) from auto_id where name=','");
        assertThat((Long)response.rows()[0][0], is(1L)); // FOUND ONE
    }
}

@@ -1056,35 +1056,8 @@
 s;%0A%0A
-import io.crate.Constants;%0A
 impo
@@ -1158,178 +1158,8 @@
 st;%0A
-import org.elasticsearch.action.count.CountRequest;%0Aimport org.elasticsearch.action.count.CountResponse;%0Aimport org.elasticsearch.action.count.CrateTransportCountAction;%0A
 impo
@@ -3238,658 +3238,8 @@
  ONE
-%0A%0A        CrateTransportCountAction action = cluster().getInstance(CrateTransportCountAction.class);%0A        CountResponse response1 = action.execute(%0A                new CountRequest(%22count_routing%22)%0A                        .types(Constants.DEFAULT_MAPPING_TYPE)%0A                        .routing(%221,2%22)%0A        ).actionGet();%0A        assertThat(response1.getCount(), is(1L));%0A%0A        CountResponse response2 = action.execute(%0A                new CountRequest(%22count_routing%22)%0A                        .types(Constants.DEFAULT_MAPPING_TYPE)%0A                        .routing(%22%22)%0A        ).actionGet();%0A        assertThat(response2.getCount(), is(1L));
 %0A   

remove CrateTransportCountAction calls from testCountRouting