/*
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed 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.
 * </p>
 */

package com.dangdang.ddframe.rdb.sharding.routing.strategy.inline;

import com.dangdang.ddframe.rdb.sharding.api.strategy.ListShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.PreciseShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.routing.strategy.ShardingStrategy;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.GroovyShell;
import groovy.util.Expando;
import lombok.Getter;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

/**
 * Standard sharding strategy.
 * 
 * @author zhangliang
 */
@Getter
public final class InlineShardingStrategy implements ShardingStrategy {
    
    private final String shardingColumn;
    
    private final Closure<?> closureTemplate;
    
    // TODO should config from sharding prop
    private final String logRoot = "logRoot";
    
    public InlineShardingStrategy(final String shardingColumn, final String inlineExpression) {
        this.shardingColumn = shardingColumn;
        Binding binding = new Binding();
        binding.setVariable("log", LoggerFactory.getLogger(logRoot.trim()));
        closureTemplate = (Closure) new GroovyShell(binding).evaluate(Joiner.on("").join("{it -> \"", inlineExpression.trim(), "\"}"));
    }
    
    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingValue> shardingValues) {
        ShardingValue shardingValue = shardingValues.iterator().next();
        Preconditions.checkState(shardingValue instanceof ListShardingValue, "Inline strategy cannot support range sharding.");
        Collection<String> shardingResult = doSharding((ListShardingValue) shardingValue);
        Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        result.addAll(shardingResult);
        return result;
    }
    
    private Collection<String> doSharding(final ListShardingValue shardingValue) {
        Collection<String> result = new LinkedList<>();
        for (PreciseShardingValue<?> eachTableShardingValue : transferToPreciseShardingValues(shardingValue)) {
            result.add(eval(eachTableShardingValue));
        }
        return result;
    }
    
    @SuppressWarnings("unchecked")
    private List<PreciseShardingValue> transferToPreciseShardingValues(final ListShardingValue<?> shardingValue) {
        List<PreciseShardingValue> result = new ArrayList<>(shardingValue.getValues().size());
        for (Comparable<?> each : shardingValue.getValues()) {
            result.add(new PreciseShardingValue(shardingValue.getLogicTableName(), shardingValue.getColumnName(), each));
        }
        return result;
    }
    
    private String eval(final PreciseShardingValue shardingValue) {
        Closure<?> result = closureTemplate.rehydrate(new Expando(), null, null);
        result.setResolveStrategy(Closure.DELEGATE_ONLY);
        result.setProperty("log", closureTemplate.getProperty("log"));
        result.setProperty(shardingValue.getColumnName(), shardingValue.getValue());
        return result.call().toString();
    }
    
    @Override
    public Collection<String> getShardingColumns() {
        Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        result.add(shardingColumn);
        return result;
    }
}

@@ -1058,36 +1058,8 @@
 ns;%0A
-import groovy.lang.Binding;%0A
 impo
@@ -1082,16 +1082,16 @@
 losure;%0A
+
 import g
@@ -1145,62 +1145,8 @@
 ndo;
-%0Aimport lombok.Getter;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aim
@@ -1348,16 +1348,8 @@
  */%0A
-@Getter%0A
 publ
@@ -1507,112 +1507,8 @@
 sure
-Template;%0A    %0A    // TODO should config from sharding prop%0A    private final String logRoot = %22logRoot%22
 ;%0A  
@@ -1656,126 +1656,8 @@
 mn;%0A
-        Binding binding = new Binding();%0A        binding.setVariable(%22log%22, LoggerFactory.getLogger(logRoot.trim()));%0A
     
@@ -1667,24 +1667,16 @@
  closure
-Template
  = (Clos
@@ -1700,15 +1700,8 @@
 ell(
-binding
 ).ev
@@ -2657,19 +2657,22 @@
 lt.add(e
-val
+xecute
 (eachTab
@@ -3228,19 +3228,22 @@
 String e
-val
+xecute
 (final P
@@ -3314,24 +3314,16 @@
  closure
-Template
 .rehydra
@@ -3415,79 +3415,8 @@
 Y);%0A
-        result.setProperty(%22log%22, closureTemplate.getProperty(%22log%22));%0A
     

remove logRoot for inline expression