001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
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 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
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 com.agentsflex.core.store.condition;
017
018import java.util.StringJoiner;
019
020public interface ExpressionAdaptor {
021
022    ExpressionAdaptor DEFAULT = new ExpressionAdaptor() {
023    };
024
025    default String toCondition(Condition condition) {
026        return toLeft(condition.left)
027            + toOperationSymbol(condition.type)
028            + toRight(condition.right);
029    }
030
031    default String toLeft(Operand operand) {
032        return operand.toExpression(this);
033    }
034
035    default String toOperationSymbol(ConditionType type) {
036        return type.getDefaultSymbol();
037    }
038
039    default String toRight(Operand operand) {
040        return operand.toExpression(this);
041    }
042
043    default String toValue(Condition condition, Object value) {
044        // between
045        if (condition.getType() == ConditionType.BETWEEN) {
046            Object[] values = (Object[]) value;
047            return "\"" + values[0] + "\" AND \"" + values[1] + "\"";
048        }
049
050        // in
051        else if (condition.getType() == ConditionType.IN) {
052            Object[] values = (Object[]) value;
053            StringJoiner stringJoiner = new StringJoiner(",", "(", ")");
054            for (Object v : values) {
055                if (v != null) {
056                    stringJoiner.add("\"" + v + "\"");
057                }
058            }
059            return stringJoiner.toString();
060        }
061
062        return value == null ? "" : "\"" + value + "\"";
063    }
064
065
066    default String toConnector(Connector connector) {
067        return connector.getValue();
068    }
069
070    default String toGroupStart(Group group) {
071        return "(";
072    }
073
074    default String toGroupEnd(Group group) {
075        return ")";
076    }
077
078
079}