/*
 * 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.util;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import groovy.lang.GString;
import groovy.lang.GroovyShell;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * Inline expression parser.
 * 
 * @author gaohongtao
 * @author zhangliang
 */
@RequiredArgsConstructor
public final class InlineExpressionParser {
    
    private static final char SPLITTER = ',';
    
    private final String inlineExpression;
    
    /**
     * Split and evaluate inline expression.
     *
     * @return result list
     */
    public List<String> evaluate() {
        final GroovyShell shell = new GroovyShell();
        return flattenSegments(Lists.transform(split(), new Function<String, Object>() {
            
            @Override
            public Object apply(final String input) {
                StringBuilder expression = new StringBuilder(input);
                if (!input.startsWith("\"")) {
                    expression.insert(0, "\"");
                }
                if (!input.endsWith("\"")) {
                    expression.append("\"");
                }
                return shell.evaluate(expression.toString());
            }
        }));
    }
    
    private List<String> split() {
        List<String> result = new ArrayList<>();
        StringBuilder segment = new StringBuilder();
        int bracketsDepth = 0;
        for (int i = 0; i < inlineExpression.length(); i++) {
            char each = inlineExpression.charAt(i);
            switch (each) {
                case SPLITTER:
                    if (bracketsDepth > 0) {
                        segment.append(each);
                    } else {
                        result.add(segment.toString().trim());
                        segment.setLength(0);
                    }
                    break;
                case '$':
                    if ('{' == inlineExpression.charAt(i + 1)) {
                        bracketsDepth++;
                    }
                    segment.append(each);
                    break;
                case '}':
                    if (bracketsDepth > 0) {
                        bracketsDepth--;
                    }
                    segment.append(each);
                    break;
                default:
                    segment.append(each);
                    break;
            }
        }
        if (segment.length() > 0) {
            result.add(segment.toString().trim());
        }
        return result;
    }
    
    private List<String> flattenSegments(final List<Object> segments) {
        List<String> result = new ArrayList<>();
        for (Object each : segments) {
            if (each instanceof GString) {
                result.addAll(assemblyCartesianSegments((GString) each));
            } else {
                result.add(each.toString());
            }
        }
        return result;
    }
    
    private List<String> assemblyCartesianSegments(final GString segment) {
        Set<List<String>> cartesianValues = getCartesianValues(segment);
        List<String> result = new ArrayList<>(cartesianValues.size());
        for (List<String> each : cartesianValues) {
            result.add(assemblySegment(each, segment));
        }
        return result;
    }
    
    @SuppressWarnings("unchecked")
    private Set<List<String>> getCartesianValues(final GString segment) {
        List<Set<String>> result = new ArrayList<>(segment.getValues().length);
        for (Object each : segment.getValues()) {
            if (null == each) {
                continue;
            }
            if (each instanceof Collection) {
                result.add(Sets.newHashSet(Collections2.transform((Collection<Object>) each, new Function<Object, String>() {
                    
                    @Override
                    public String apply(final Object input) {
                        return input.toString();
                    }
                })));
            } else {
                result.add(Sets.newHashSet(each.toString()));
            }
        }
        return Sets.cartesianProduct(result);
    }
    
    private String assemblySegment(final List<String> cartesianValue, final GString segment) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < segment.getStrings().length; i++) {
            result.append(segment.getStrings()[i]);
            if (i < cartesianValue.size()) {
                result.append(cartesianValue.get(i));
            }
        }
        return result.toString();
    }
}

@@ -749,48 +749,8 @@
 s2;%0A
-import com.google.common.collect.Lists;%0A
 impo
@@ -1389,235 +1389,296 @@
     
-final GroovyShell shell = new GroovyShell(
+return flatten(evaluate(split())
 );%0A    
+%7D%0A
     
-return flattenSegments(Lists.transform(split(), new Function%3CString, Object%3E() %7B%0A            %0A            @Override%0A            public Object apply(final String input) %7B%0A    
+%0A    private List%3CObject%3E evaluate(final List%3CString%3E inlineExpressions) %7B%0A        List%3CObject%3E result = new ArrayList%3C%3E(inlineExpressions.size());%0A        GroovyShell shell = new GroovyShell();%0A        for (String each : inlineExpressions) %7B%0A
     
@@ -1734,20 +1734,15 @@
 der(
-input);%0A    
+each);%0A
     
@@ -1754,21 +1754,20 @@
    if (!
-input
+each
 .startsW
@@ -1771,36 +1771,32 @@
 tsWith(%22%5C%22%22)) %7B%0A
-    
                 
@@ -1831,34 +1831,26 @@
             
- 
-   %7D%0A    
+%7D%0A
             
@@ -1854,21 +1854,20 @@
    if (!
-input
+each
 .endsWit
@@ -1869,36 +1869,32 @@
 dsWith(%22%5C%22%22)) %7B%0A
-    
                 
@@ -1926,34 +1926,26 @@
             
-    %7D%0A    
+%7D%0A
             
@@ -1946,21 +1946,25 @@
       re
-turn 
+sult.add(
 shell.ev
@@ -1984,38 +1984,35 @@
 sion.toString())
+)
 ;%0A
-    
         %7D%0A      
@@ -2013,19 +2013,29 @@
         
-%7D))
+return result
 ;%0A    %7D%0A
@@ -3365,24 +3365,16 @@
  flatten
-Segments
 (final L

refactor inline expression parser