/*
 * 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.rewrite.token.generator;

import com.google.common.base.Optional;
import org.apache.shardingsphere.core.optimize.api.statement.OptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.dml.item.ColumnSelectItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemsSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.rewrite.builder.ParameterBuilder;
import org.apache.shardingsphere.core.rewrite.token.pojo.SelectEncryptItemToken;
import org.apache.shardingsphere.core.rule.EncryptRule;

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

/**
 * Select cipher item token generator.
 *
 * @author panjuan
 */
public final class SelectEncryptItemTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> {
    
    private EncryptRule encryptRule;
    
    private OptimizedStatement optimizedStatement;
    
    private boolean isQueryWithCipherColumn;
    
    @Override
    public Collection<SelectEncryptItemToken> generateSQLTokens(final OptimizedStatement optimizedStatement,
                                                                final ParameterBuilder parameterBuilder, final EncryptRule rule, final boolean isQueryWithCipherColumn) {
        if (!isNeedToGenerateSQLToken(optimizedStatement)) {
            return Collections.emptyList();
        }
        initParameters(rule, optimizedStatement, isQueryWithCipherColumn);
        return createSelectCipherItemTokens();
    }
    
    private boolean isNeedToGenerateSQLToken(final OptimizedStatement optimizedStatement) {
        if (!isSelectStatementWithTable(optimizedStatement)) {
            return false;
        }
        Optional<SelectItemsSegment> selectItemsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SelectItemsSegment.class);
        return selectItemsSegment.isPresent() && !selectItemsSegment.get().getSelectItems().isEmpty();
    }
    
    private boolean isSelectStatementWithTable(final OptimizedStatement optimizedStatement) {
        return optimizedStatement.getSQLStatement() instanceof SelectStatement && !optimizedStatement.getTables().isEmpty();
    }
    
    private void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) {
        encryptRule = rule;
        this.optimizedStatement = optimizedStatement;
        this.isQueryWithCipherColumn = isQueryWithCipherColumn;
    }
    
    private Collection<SelectEncryptItemToken> createSelectCipherItemTokens() {
        Collection<SelectEncryptItemToken> result = new LinkedList<>();
        SelectItemsSegment selectItemsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SelectItemsSegment.class).get();
        String tableName = optimizedStatement.getTables().getSingleTableName();
        Collection<String> logicColumns = encryptRule.getLogicColumns(tableName);
        for (SelectItemSegment each : selectItemsSegment.getSelectItems()) {
            if (isLogicColumn(each, logicColumns)) {
                result.add(createSelectCipherItemToken(each, tableName));
            }
        }
        return result;
    }
    
    private boolean isLogicColumn(final SelectItemSegment each, final Collection<String> logicColumns) {
        return each instanceof ColumnSelectItemSegment && logicColumns.contains(((ColumnSelectItemSegment) each).getName());
    }
    
    private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName) {
        String columnName = ((ColumnSelectItemSegment) each).getName();
        Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, columnName);
        if (!isQueryWithCipherColumn && plainColumn.isPresent()) {
            return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), plainColumn.get());
        }
        return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), encryptRule.getCipherColumn(tableName, columnName));
    }
}

@@ -1802,156 +1802,8 @@
    %0A
-    private EncryptRule encryptRule;%0A    %0A    private OptimizedStatement optimizedStatement;%0A    %0A    private boolean isQueryWithCipherColumn;%0A    %0A
     
@@ -1812,16 +1812,16 @@
 verride%0A
+
     publ
@@ -2214,29 +2214,50 @@
         
-initParameter
+return createSelectCipherItemToken
 s(rule, 
@@ -2306,55 +2306,8 @@
 n);%0A
-        return createSelectCipherItemTokens();%0A
     
@@ -3001,180 +3001,110 @@
 ate 
-void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) %7B%0A        encryptRule = rule;%0A        this.o
+Collection%3CSelectEncryptItemToken%3E createSelectCipherItemTokens(final EncryptRule encryptRule, final O
 ptim
@@ -3112,26 +3112,24 @@
 zedStatement
- =
  optimizedSt
@@ -3139,161 +3139,47 @@
 ment
-;%0A        this.isQueryWithCipherColumn = isQueryWithCipherColumn;%0A    %7D%0A    %0A    private Collection%3CSelectEncryptItemToken%3E createSelectCipherItemTokens(
+, final boolean isQueryWithCipherColumn
 ) %7B%0A
@@ -3741,24 +3741,62 @@
 h, tableName
+, encryptRule, isQueryWithCipherColumn
 ));%0A        
@@ -4078,32 +4078,32 @@
 ());%0A    %7D%0A    %0A
-
     private Sele
@@ -4201,16 +4201,86 @@
 ableName
+, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn
 ) %7B%0A    

delete members for SelectEncryptItemTokenGenerator