/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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.apache.shardingsphere.sharding.algorithm.sharding.inline;

import com.google.common.base.Preconditions;
import groovy.lang.Closure;
import groovy.util.Expando;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.apache.shardingsphere.sharding.support.InlineExpressionParser;

import java.util.Collection;
import java.util.Properties;

/**
 * Inline sharding algorithm.
 */
public final class InlineShardingAlgorithm implements StandardShardingAlgorithm<Comparable<?>> {
    
    private static final String ALGORITHM_EXPRESSION_KEY = "algorithm-expression";
    
    private static final String ALLOW_RANGE_QUERY_KEY = "allow-range-query-with-inline-sharding";
    
    private String algorithmExpression;
    
    private boolean allowRangeQuery;
    
    @Getter
    @Setter
    private Properties props = new Properties();
    
    @Override
    public void init() {
        algorithmExpression = getAlgorithmExpression();
        allowRangeQuery = isAllowRangeQuery();
    }
    
    private String getAlgorithmExpression() {
        String expression = props.getProperty(ALGORITHM_EXPRESSION_KEY);
        Preconditions.checkNotNull(expression, "Inline sharding algorithm expression cannot be null.");
        return InlineExpressionParser.handlePlaceHolder(expression.trim());
    }
    
    private boolean isAllowRangeQuery() {
        return Boolean.parseBoolean(props.getOrDefault(ALLOW_RANGE_QUERY_KEY, Boolean.FALSE.toString()).toString());
    }
    
    @Override
    public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
        Closure<?> closure = createClosure();
        closure.setProperty(shardingValue.getColumnName(), shardingValue.getValue());
        return closure.call().toString();
    }
    
    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Comparable<?>> shardingValue) {
        if (allowRangeQuery) {
            return availableTargetNames;
        }
        throw new UnsupportedOperationException("Since the property of `" + ALLOW_RANGE_QUERY_KEY + "` is false, inline sharding algorithm can not tackle with range query.");
    }
    
    private Closure<?> createClosure() {
        Closure<?> result = new InlineExpressionParser(algorithmExpression).evaluateClosure().rehydrate(new Expando(), null, null);
        result.setResolveStrategy(Closure.DELEGATE_ONLY);
        return result;
    }
    
    @Override
    public String getType() {
        return "INLINE";
    }
}

@@ -940,16 +940,59 @@
 losure;%0A
+import groovy.lang.MissingMethodException;%0A
 import g
@@ -1051,24 +1051,98 @@
 bok.Setter;%0A
+import org.apache.shardingsphere.infra.exception.ShardingSphereException;%0A
 import org.a
@@ -2323,26 +2323,57 @@
 heck
-NotNull(expression
+State(null != expression && !expression.isEmpty()
 , %22I
@@ -2422,16 +2422,25 @@
  be null
+ or empty
 .%22);%0A   
@@ -2993,32 +2993,68 @@
 urn 
-closure.call().toString(
+getTargetShardingNode(closure, shardingValue.getColumnName()
 );%0A 
@@ -3747,32 +3747,444 @@
 ult;%0A    %7D%0A    %0A
+    private String getTargetShardingNode(final Closure%3C?%3E closure, final String columnName) %7B%0A        try %7B%0A            return closure.call().toString();%0A        %7D catch (final MissingMethodException %7C NullPointerException ex) %7B%0A            throw new ShardingSphereException(%22Inline sharding algorithms expression %60%25s%60 and sharding column %60%25s%60 not match.%22, algorithmExpression, columnName);%0A        %7D%0A    %7D%0A    %0A
     @Override%0A  

Optimize error messages when inline algorithm expression and sharding column not match. (#15176)