/*
 * 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.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.rewrite.builder.ParameterBuilder;
import org.apache.shardingsphere.core.rewrite.token.pojo.InsertSetAddGeneratedKeyToken;
import org.apache.shardingsphere.core.rule.ShardingRule;

import java.util.ArrayList;
import java.util.List;

/**
 * Insert set add items token generator.
 *
 * @author panjuan
 */
public final class InsertSetAddGeneratedKeyTokenGenerator implements OptionalSQLTokenGenerator<ShardingRule> {
    
    @Override
    public Optional<InsertSetAddGeneratedKeyToken> generateSQLToken(final OptimizedStatement optimizedStatement, final ParameterBuilder parameterBuilder, final ShardingRule shardingRule) {
        Optional<SetAssignmentsSegment> setAssignmentsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SetAssignmentsSegment.class);
        if (!(optimizedStatement.getSQLStatement() instanceof InsertStatement && setAssignmentsSegment.isPresent())) {
            return Optional.absent();
        }
        return createInsertSetAddGeneratedKeyToken((ShardingInsertOptimizedStatement) optimizedStatement, shardingRule, setAssignmentsSegment.get());
    }
    
    private Optional<InsertSetAddGeneratedKeyToken> createInsertSetAddGeneratedKeyToken(
            final ShardingInsertOptimizedStatement optimizedStatement, final ShardingRule shardingRule, final SetAssignmentsSegment segment) {
        Optional<String> generatedKeyColumn = getGeneratedKeyColumn((InsertStatement) optimizedStatement.getSQLStatement(), shardingRule);
        if (generatedKeyColumn.isPresent()) {
            return Optional.of(createInsertSetAddGeneratedKeyToken(optimizedStatement, generatedKeyColumn.get(), new ArrayList<>(segment.getAssignments())));
        }
        return Optional.absent();
    }
    
    private InsertSetAddGeneratedKeyToken createInsertSetAddGeneratedKeyToken(
            final ShardingInsertOptimizedStatement optimizedStatement, final String generatedKeyColumn, final List<AssignmentSegment> assignments) {
        return new InsertSetAddGeneratedKeyToken(
                assignments.get(assignments.size() - 1).getStopIndex() + 1, generatedKeyColumn, optimizedStatement.getUnits().get(0).getColumnSQLExpression(generatedKeyColumn));
    }
    
    private Optional<String> getGeneratedKeyColumn(final InsertStatement insertStatement, final ShardingRule shardingRule) {
        Optional<String> generateKeyColumn = shardingRule.findGenerateKeyColumnName(insertStatement.getTables().getSingleTableName());
        return generateKeyColumn.isPresent() && !insertStatement.getColumnNames().contains(generateKeyColumn.get()) ? generateKeyColumn : Optional.<String>absent();
    }
}

@@ -958,16 +958,22 @@
 atement.
+Insert
 Optimize
@@ -1045,42 +1045,8 @@
 ent.
-sharding.dml.insert.ShardingInsert
 Opti
@@ -1249,87 +1249,8 @@
 nt;%0A
-import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;%0A
 impo
@@ -2083,34 +2083,16 @@
 tatement
-.getSQLStatement()
  instanc
@@ -2097,24 +2097,33 @@
 nceof Insert
+Optimized
 Statement &&
@@ -2261,24 +2261,16 @@
 yToken((
-Sharding
 InsertOp
@@ -2465,32 +2465,24 @@
       final 
-Sharding
 InsertOptimi
@@ -2658,62 +2658,26 @@
 umn(
-(InsertStatement) optimizedStatement.getSQLStatement()
+optimizedStatement
 , sh
@@ -3045,24 +3045,16 @@
   final 
-Sharding
 InsertOp
@@ -3466,24 +3466,33 @@
 final Insert
+Optimized
 Statement in
@@ -3489,22 +3489,25 @@
 atement 
-insert
+optimized
 Statemen
@@ -3628,22 +3628,41 @@
 umnName(
-insert
+optimizedStatement.getSQL
 Statemen
@@ -3658,24 +3658,26 @@
 SQLStatement
+()
 .getTables()
@@ -3753,14 +3753,17 @@
 && !
-insert
+optimized
 Stat
@@ -3767,24 +3767,50 @@
 tatement.get
+InsertColumns().getRegular
 ColumnNames(

solve conflicts