001/*
002 *  Copyright 2021 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.cms.search.query;
017
018import java.util.Map;
019
020/**
021 * Represents a {@link Query} testing a geocode field.
022 */
023public class GeocodeQuery extends AbstractOperatorQuery<Map<String, Integer>>
024{
025    /**
026     * Build a Geocode testing the existence of the field.
027     * @param fieldPath the field path
028     */
029    public GeocodeQuery(String fieldPath)
030    {
031        this(fieldPath, Operator.EXISTS, null);
032    }
033    
034    /**
035     * Build a Geocode query.
036     * @param fieldPath the field's path
037     * @param operator the operator.
038     * @param value the value.
039     */
040    public GeocodeQuery(String fieldPath, Operator operator, Map<String, Integer> value)
041    {
042        super(fieldPath + "_geo", operator, value);
043
044        if (Operator.EQ != operator && Operator.NE != operator && Operator.EXISTS != operator)
045        {
046            throw new IllegalArgumentException("Test operator '" + operator + "' is unknown for test's expression.");
047        }
048    }
049    
050    @Override
051    public String build() throws QuerySyntaxException
052    {
053        Operator operator = getOperator();
054        Map<String, Integer> value = getValue();
055        
056        StringBuilder query = new StringBuilder();
057        
058        if (operator == Operator.EXISTS)
059        {
060            query.append(getFieldName()).append(":*");
061            return query.toString();
062        }
063        
064        if (operator == Operator.NE)
065        {
066            NotQuery.appendNegation(query);
067        }
068        
069        query.append(getFieldName()).append(":[")
070        .append(value.get("latitude")).append(",").append(value.get("longitude"))
071        .append(" TO ")
072        .append(value.get("latitude")).append(",").append(value.get("longitude"))
073        .append("]");
074        return query.toString();
075    }
076}