/*
 * 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.statement.OptimizedStatement;
import org.apache.shardingsphere.core.optimize.statement.sharding.dml.insert.ShardingInsertOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.dml.assignment.AssignmentSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.assignment.SetAssignmentsSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.ParameterMarkerExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.rewrite.token.pojo.InsertSetEncryptValueToken;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;

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

/**
 * Insert set encrypt value token generator.
 *
 * @author panjuan
 */
public final class InsertSetEncryptValueTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> {
    
    @Override
    public Collection<InsertSetEncryptValueToken> generateSQLTokens(final OptimizedStatement optimizedStatement, final List<Object> parameters, final EncryptRule encryptRule) {
        Optional<SetAssignmentsSegment> setAssignmentsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SetAssignmentsSegment.class);
        if (!(optimizedStatement.getSQLStatement() instanceof InsertStatement && setAssignmentsSegment.isPresent())) {
            return Collections.emptyList();
        }
        return createInsertSetEncryptValueTokens(
                (InsertStatement) optimizedStatement.getSQLStatement(), encryptRule, (ShardingInsertOptimizedStatement) optimizedStatement, setAssignmentsSegment.get());
    }
    
    private Collection<InsertSetEncryptValueToken> createInsertSetEncryptValueTokens(
            final InsertStatement insertStatement, final EncryptRule encryptRule, final ShardingInsertOptimizedStatement optimizedStatement, final SetAssignmentsSegment segment) {
        Collection<InsertSetEncryptValueToken> result = new LinkedList<>();
        for (AssignmentSegment each : segment.getAssignments()) {
            Optional<InsertSetEncryptValueToken> insertSetEncryptValueToken = createInsertSetEncryptValueToken(insertStatement, encryptRule, optimizedStatement, each);
            if (insertSetEncryptValueToken.isPresent()) {
                result.add(insertSetEncryptValueToken.get());
            }
        }
        return result;
    }
    
    private Optional<InsertSetEncryptValueToken> createInsertSetEncryptValueToken(
            final InsertStatement insertStatement, final EncryptRule encryptRule, final ShardingInsertOptimizedStatement optimizedStatement, final AssignmentSegment segment) {
        Optional<ShardingEncryptor> shardingEncryptor = encryptRule.getEncryptorEngine().getShardingEncryptor(insertStatement.getTables().getSingleTableName(), segment.getColumn().getName());
        if (shardingEncryptor.isPresent() && !(segment.getValue() instanceof ParameterMarkerExpressionSegment)) {
            return Optional.of(new InsertSetEncryptValueToken(
                    segment.getValue().getStartIndex(), segment.getValue().getStopIndex(), optimizedStatement.getUnits().get(0).getColumnSQLExpression(segment.getColumn().getName())));
        }
        return Optional.absent();
    }
}

@@ -2528,129 +2528,8 @@
 ens(
-%0A                (InsertStatement) optimizedStatement.getSQLStatement(), encryptRule, (ShardingInsertOptimizedStatement) 
 opti
@@ -2542,16 +2542,29 @@
 tatement
+, encryptRule
 , setAss
@@ -2687,33 +2687,23 @@
 ens(
-%0A            final Insert
+final Optimized
 Stat
@@ -2700,38 +2700,41 @@
 imizedStatement 
-insert
+optimized
 Statement, final
@@ -2762,67 +2762,8 @@
 ule,
- final ShardingInsertOptimizedStatement optimizedStatement,
  fin
@@ -3051,22 +3051,25 @@
 ueToken(
-insert
+optimized
 Statemen
@@ -3083,36 +3083,16 @@
 yptRule,
- optimizedStatement,
  each);%0A
@@ -3355,33 +3355,23 @@
 ken(
-%0A            final Insert
+final Optimized
 Stat
@@ -3376,22 +3376,25 @@
 atement 
-insert
+optimized
 Statemen
@@ -3430,67 +3430,8 @@
 ule,
- final ShardingInsertOptimizedStatement optimizedStatement,
  fin
@@ -3518,16 +3518,33 @@
 yptor = 
+%0A                
 encryptR
@@ -3589,22 +3589,41 @@
 cryptor(
-insert
+optimizedStatement.getSQL
 Statemen
@@ -3619,24 +3619,26 @@
 SQLStatement
+()
 .getTables()
@@ -3872,29 +3872,8 @@
 ken(
-%0A                    
 segm
@@ -3900,24 +3900,45 @@
 artIndex(), 
+%0A                    
 segment.getV
@@ -3959,16 +3959,52 @@
 Index(),
+ ((ShardingInsertOptimizedStatement)
  optimiz
@@ -4010,24 +4010,25 @@
 zedStatement
+)
 .getUnits().

optimize it