/*
 * 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.core.execute.sql.execute.result;

import com.google.common.base.Optional;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.core.strategy.encrypt.ShardingEncryptorEngine;
import org.apache.shardingsphere.core.strategy.encrypt.ShardingEncryptorStrategy;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map.Entry;

/**
 * Query result meta data.
 *
 * @author panjuan
 */
public final class QueryResultMetaData {
    
    private final Multimap<String, Integer> columnLabelAndIndexes;
    
    private final ResultSetMetaData resultSetMetaData;
    
    private final ShardingRule shardingRule;
    
    private final ShardingEncryptorEngine shardingEncryptorEngine;
    
    @SneakyThrows 
    public QueryResultMetaData(final ResultSetMetaData resultSetMetaData, final ShardingRule shardingRule, final ShardingEncryptorEngine shardingEncryptorEngine) {
        columnLabelAndIndexes = getColumnLabelAndIndexMap(resultSetMetaData);
        this.resultSetMetaData = resultSetMetaData;
        this.shardingRule = shardingRule;
        this.shardingEncryptorEngine = shardingEncryptorEngine;
    }
    
    @SneakyThrows
    public QueryResultMetaData(final ResultSetMetaData resultSetMetaData) {
        this(resultSetMetaData, null, new ShardingEncryptorEngine(Collections.<String, ShardingEncryptorStrategy>emptyMap()));
    }
    
    @SneakyThrows
    private Multimap<String, Integer> getColumnLabelAndIndexMap(final ResultSetMetaData resultSetMetaData) {
        Multimap<String, Integer> result = HashMultimap.create();
        for (int columnIndex = 1; columnIndex <= resultSetMetaData.getColumnCount(); columnIndex++) {
            result.put(resultSetMetaData.getColumnLabel(columnIndex), columnIndex);
        }
        return result;
    }
    
    /**
     * Get column count.
     * 
     * @return column count
     */
    public int getColumnCount() {
        return columnLabelAndIndexes.size();
    }
    
    /**
     * Get column label.
     * 
     * @param columnIndex column index
     * @return column label
     */
    @SneakyThrows
    public String getColumnLabel(final int columnIndex) {
        for (Entry<String, Integer> entry : columnLabelAndIndexes.entries()) {
            if (columnIndex == entry.getValue()) {
                return entry.getKey();
            }
        }
        throw new SQLException("Column index out of range", "9999");
    }
    
    /**
     * Get column name.
     * 
     * @param columnIndex column index
     * @return column name
     */
    @SneakyThrows
    public String getColumnName(final int columnIndex) {
        return resultSetMetaData.getColumnName(columnIndex);
    }
    
    /**
     * Get column index.
     * 
     * @param columnLabel column label
     * @return column name
     */
    public Integer getColumnIndex(final String columnLabel) {
        return new ArrayList<>(columnLabelAndIndexes.get(columnLabel)).get(0);
    }
    
    /**
     * Get sharding encryptor.
     * 
     * @param columnIndex column index
     * @return sharding encryptor optional
     */
    @SneakyThrows
    public Optional<ShardingEncryptor> getShardingEncryptor(final int columnIndex) {
        return shardingEncryptorEngine.getShardingEncryptor(getTableName(columnIndex), resultSetMetaData.getColumnName(columnIndex));
    }
    
    private String getTableName(final int columnIndex) throws SQLException {
        String actualTableName = resultSetMetaData.getTableName(columnIndex);
        if (null == shardingRule) {
            return actualTableName;
        }
        Optional<TableRule> tableRule = shardingRule.findTableRuleByActualTable(actualTableName);
        return tableRule.isPresent() ? tableRule.get().getLogicTable() : actualTableName;
    }
}

@@ -908,98 +908,8 @@
 al;%0A
-import com.google.common.collect.HashMultimap;%0Aimport com.google.common.collect.Multimap;%0A
 impo
@@ -932,16 +932,16 @@
 Throws;%0A
+
 import o
@@ -1339,36 +1339,8 @@
 on;%0A
-import java.util.ArrayList;%0A
 impo
@@ -1389,14 +1389,34 @@
 .Map
-.Entry
+;%0Aimport java.util.TreeMap
 ;%0A%0A/
@@ -1536,21 +1536,16 @@
  final M
-ultim
 ap%3CStrin
@@ -2459,21 +2459,16 @@
 rivate M
-ultim
 ap%3CStrin
@@ -2559,21 +2559,16 @@
        M
-ultim
 ap%3CStrin
@@ -2592,28 +2592,51 @@
 t = 
-HashMultimap.create(
+new TreeMap%3C%3E(String.CASE_INSENSITIVE_ORDER
 );%0A 
@@ -2668,26 +2668,8 @@
 ex =
- 1; columnIndex %3C=
  res
@@ -2716,10 +2716,27 @@
 ndex
-++
+ %3E 0; columnIndex--
 ) %7B%0A
@@ -2932,32 +2932,50 @@
 n count%0A     */%0A
+    @SneakyThrows%0A
     public int g
@@ -3011,34 +3011,40 @@
 urn 
-columnLabelAndIndexes.size
+resultSetMetaData.getColumnCount
 ();%0A
@@ -3258,259 +3258,59 @@
     
-for (Entry%3CString, Integer%3E entry : columnLabelAndIndexes.entries()) %7B%0A            if (columnIndex == entry.getValue()) %7B%0A                return entry.getKey();%0A            %7D%0A        %7D%0A        throw new SQLException(%22C
+return resultSetMetaData.getColumnLabel(c
 olumn
- i
+I
 ndex
- out of range%22, %229999%22
 );%0A 
@@ -3776,24 +3776,8 @@
 urn 
-new ArrayList%3C%3E(
 colu
@@ -3814,16 +3814,8 @@
 bel)
-).get(0)
 ;%0A  

Fix #2152