/*
 * 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.parse.sql.statement;

import com.google.common.base.Optional;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.apache.shardingsphere.core.constant.SQLType;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.core.parse.sql.context.condition.Condition;
import org.apache.shardingsphere.core.parse.sql.context.condition.ParseCondition;
import org.apache.shardingsphere.core.parse.sql.context.table.Tables;
import org.apache.shardingsphere.core.parse.sql.segment.SQLSegment;
import org.apache.shardingsphere.core.parse.sql.token.SQLToken;
import org.apache.shardingsphere.core.parse.sql.token.impl.EncryptColumnToken;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * SQL statement abstract class.
 *
 * @author zhangliang
 * @author panjuan
 */
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public abstract class AbstractSQLStatement implements SQLStatement {
    
    private final SQLType type;
    
    private final Collection<SQLSegment> sqlSegments = new LinkedList<>();
    
    private final Tables tables = new Tables();
    
    private final ParseCondition routeCondition = new ParseCondition();
    
    private final ParseCondition encryptCondition = new ParseCondition();
    
    @Getter(AccessLevel.NONE)
    private final List<SQLToken> sqlTokens = new LinkedList<>();
    
    private int parametersIndex;
    
    private String logicSQL;
    
    @Override
    public final void addSQLToken(final SQLToken sqlToken) {
        sqlTokens.add(sqlToken);
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public final <T extends SQLToken> Optional<T> findSQLToken(final Class<T> sqlTokenType) {
        for (SQLToken each : sqlTokens) {
            if (each.getClass().equals(sqlTokenType)) {
                return Optional.of((T) each);
            }
        }
        return Optional.absent();
    }
    
    @Override
    public final List<SQLToken> getSQLTokens() {
        Collections.sort(sqlTokens);
        return sqlTokens;
    }
    
    /**
     * Get encrypt condition.
     * 
     * @param encryptColumnToken encrypt column token
     * @return encrypt condition
     */
    public Optional<Condition> getEncryptCondition(final EncryptColumnToken encryptColumnToken) {
        List<Condition> conditions = encryptCondition.findConditions(encryptColumnToken.getColumn());
        if (conditions.isEmpty()) {
            return Optional.absent();
        }
        if (1 == conditions.size()) {
            return Optional.of(conditions.iterator().next());
        }
        return Optional.of(conditions.get(getEncryptConditionIndex(encryptColumnToken)));
    }
    
    private int getEncryptConditionIndex(final EncryptColumnToken encryptColumnToken) {
        int result = 0;
        for (SQLToken each : sqlTokens) {
            if (each.equals(encryptColumnToken)) {
                return result;
            } else if (each instanceof EncryptColumnToken) {
                result++;
            }
        }
        throw new ShardingException("Index Out Of Bounds For sqlTokens.");
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public final <T extends SQLSegment> Optional<T> findSQLSegment(final Class<T> sqlSegmentType) {
        for (SQLSegment each : sqlSegments) {
            if (each.getClass().equals(sqlSegmentType)) {
                return Optional.of((T) each);
            }
        }
        return Optional.absent();
    }
}

@@ -1091,75 +1091,8 @@
 pe;%0A
-import org.apache.shardingsphere.core.exception.ShardingException;%0A
 impo
@@ -1384,16 +1384,98 @@
 egment;%0A
+import org.apache.shardingsphere.core.parse.sql.segment.dml.column.ColumnSegment;%0A
 import o
@@ -3289,21 +3289,21 @@
         
-List%3C
+for (
 Conditio
@@ -3307,22 +3307,15 @@
 tion
-%3E conditions =
+ each :
  enc
@@ -3374,18 +3374,24 @@
 olumn())
-;%0A
+) %7B%0A    
         
@@ -3398,32 +3398,78 @@
 if (
-conditions.isEmpty()) %7B%0A
+isSameColumnIndex(each.getColumnSegment(), encryptColumnToken)) %7B%0A    
     
@@ -3488,34 +3488,38 @@
 rn Optional.
-absent();%0A
+of(each);%0A    
         %7D%0A  
@@ -3528,104 +3528,44 @@
     
-if (1 == conditions.size()) %7B%0A            return Optional.of(conditions.iterator().nex
+%7D%0A        return Optional.absen
 t()
-)
 ;%0A
-    
     
@@ -3574,524 +3574,279 @@
     
+%0A
     
-return Optional.of(conditions.get(getEncryptConditionIndex(encryptColumnToken)));%0A    %7D%0A    %0A    private int getEncryptConditionIndex(final EncryptColumnToken encryptColumnToken) %7B%0A        int result = 0;%0A        for (SQLToken each : sqlTokens) %7B%0A            if (each.equals(encryptColumnToken)) %7B%0A                return result;%0A            %7D else if (each instanceof EncryptColumnToken) %7B%0A                result++;%0A            %7D%0A        %7D%0A        throw new ShardingException(%22Index Out Of Bounds For sqlTokens.%22
+private boolean isSameColumnIndex(final ColumnSegment columnSegment, final EncryptColumnToken encryptColumnToken) %7B%0A        return columnSegment.getStartIndex() == encryptColumnToken.getStartIndex() && columnSegment.getStopIndex() == encryptColumnToken.getStopIndex(
 );%0A 

add isSameColumnIndex()