/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.
 */

package org.elasticsearch.index.query;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.index.mapper.MappedFieldType;

import com.fasterxml.jackson.core.io.JsonStringEncoder;

import java.io.IOException;

import static org.hamcrest.Matchers.either;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.is;

public class TermQueryBuilderTests extends AbstractTermQueryTestCase<TermQueryBuilder> {

    @Override
    protected TermQueryBuilder doCreateTestQueryBuilder() {
        String fieldName = null;
        Object value;
        switch (randomIntBetween(0, 3)) {
            case 0:
                if (randomBoolean()) {
                    fieldName = BOOLEAN_FIELD_NAME;
                }
                value = randomBoolean();
                break;
            case 1:
                if (randomBoolean()) {
                    fieldName = STRING_FIELD_NAME;
                }
                if (frequently()) {
                    value = randomAsciiOfLengthBetween(1, 10);
                } else {
                    // generate unicode string in 10% of cases
                    JsonStringEncoder encoder = JsonStringEncoder.getInstance();
                    value = new String(encoder.quoteAsString(randomUnicodeOfLength(10)));
                }
                break;
            case 2:
                if (randomBoolean()) {
                    fieldName = INT_FIELD_NAME;
                }
                value = randomInt(10000);
                break;
            case 3:
                if (randomBoolean()) {
                    fieldName = DOUBLE_FIELD_NAME;
                }
                value = randomDouble();
                break;
            default:
                throw new UnsupportedOperationException();
        }

        if (fieldName == null) {
            fieldName = randomAsciiOfLengthBetween(1, 10);
        }
        return createQueryBuilder(fieldName, value);
    }

    /**
     * @return a TermQuery with random field name and value, optional random boost and queryname
     */
    @Override
    protected TermQueryBuilder createQueryBuilder(String fieldName, Object value) {
        return new TermQueryBuilder(fieldName, value);
    }

    @Override
    protected void doAssertLuceneQuery(TermQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
        assertThat(query, either(instanceOf(TermQuery.class)).or(instanceOf(PointRangeQuery.class)));
        MappedFieldType mapper = context.fieldMapper(queryBuilder.fieldName());
        if (query instanceof TermQuery) {
            TermQuery termQuery = (TermQuery) query;
            assertThat(termQuery.getTerm().field(), equalTo(queryBuilder.fieldName()));
            if (mapper != null) {
                Term term = ((TermQuery) mapper.termQuery(queryBuilder.value(), null)).getTerm();
                assertThat(termQuery.getTerm(), equalTo(term));
            } else {
                assertThat(termQuery.getTerm().bytes(), equalTo(BytesRefs.toBytesRef(queryBuilder.value())));
            }
        } else {
            assertEquals(query, mapper.termQuery(queryBuilder.value(), null));
        }
    }

    public void testTermArray() throws IOException {
        String queryAsString = "{\n" +
                "    \"term\": {\n" +
                "        \"age\": [34, 35]\n" +
                "    }\n" +
                "}";
        try {
            parseQuery(queryAsString);
            fail("Expected ParsingException");
        } catch (ParsingException e) {
            assertThat(e.getMessage(), is("[term] query does not support array of values"));
        }
    }

    public void testFromJson() throws IOException {
        String json =
                "{\n" + 
                "  \"term\" : {\n" + 
                "    \"exact_value\" : {\n" + 
                "      \"value\" : \"Quick Foxes!\",\n" + 
                "      \"boost\" : 1.0\n" + 
                "    }\n" + 
                "  }\n" + 
                "}";

        TermQueryBuilder parsed = (TermQueryBuilder) parseQuery(json);
        checkGeneratedJson(json, parsed);

        assertEquals(json, "Quick Foxes!", parsed.value());
    }

    public void testGeo() throws Exception {
        assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
        TermQueryBuilder query = new TermQueryBuilder(GEO_POINT_FIELD_NAME, "2,3");
        QueryShardContext context = createShardContext();
        QueryShardException e = expectThrows(QueryShardException.class,
                () -> query.toQuery(context));
        assertEquals("Geo fields do not support exact searching, use dedicated geo queries instead: [mapped_geo_point]",
                e.getMessage());
    }
}

@@ -5862,11 +5862,712 @@
 );%0A    %7D
+%0A%0A    public void testParseFailsWithMultipleFields() throws IOException %7B%0A        String json = %22%7B%5Cn%22 +%0A                %22  %5C%22term%5C%22 : %7B%5Cn%22 +%0A                %22    %5C%22message1%5C%22 : %7B%5Cn%22 +%0A                %22      %5C%22value%5C%22 : %5C%22this%5C%22%5Cn%22 +%0A                %22    %7D,%5Cn%22 +%0A                %22    %5C%22message2%5C%22 : %7B%5Cn%22 +%0A                %22      %5C%22value%5C%22 : %5C%22this%5C%22%5Cn%22 +%0A                %22    %7D%5Cn%22 +%0A                %22  %7D%5Cn%22 +%0A                %22%7D%22;%0A%0A        try %7B%0A            parseQuery(json);%0A            fail(%22parseQuery should have failed%22);%0A        %7D catch(ParsingException e) %7B%0A            assertEquals(%22%5Bterm%5D query does not support different field names, use %5Bbool%5D query instead%22, e.getMessage());%0A        %7D%0A    %7D
 %0A%7D%0A

test that term query throws error when made against multiple fields