/*
 * 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.shardingjdbc.jdbc.core.statement;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.optimizer.OptimizeEngineFactory;
import org.apache.shardingsphere.core.parsing.parser.sql.SQLStatement;
import org.apache.shardingsphere.core.rewrite.EncryptSQLRewriteEngine;
import org.apache.shardingsphere.core.rewrite.SQLBuilder;
import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.AbstractShardingPreparedStatementAdapter;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.EncryptConnection;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset.EncryptResultSet;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * Encrypt prepared statement.
 *
 * @author panjuan
 */
public final class EncryptPreparedStatement extends AbstractShardingPreparedStatementAdapter {
    
    private final String sql;
    
    private final EncryptPreparedStatementGenerator preparedStatementMetaData;
    
    private EncryptResultSet resultSet;
    
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql) {
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator();
    }
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql, final int resultSetType, final int resultSetConcurrency) {
        this.connection = connection;
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator(resultSetType, resultSetConcurrency);
    }
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) {
        this.connection = connection;
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator(resultSetType, resultSetConcurrency, resultSetHoldability);
    }
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql, final int autoGeneratedKeys) {
        this.connection = connection;
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator(autoGeneratedKeys);
    }
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql, final int[] columnIndexes) {
        this.connection = connection;
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator(columnIndexes);
    }
    
    @SneakyThrows
    public EncryptPreparedStatement(final EncryptConnection connection, final String sql, final String[] columnNames) {
        this.connection = connection;
        this.sql = sql;
        preparedStatementMetaData = new EncryptPreparedStatementGenerator(columnNames);
    }
    
    @Override
    public ResultSet executeQuery() throws SQLException {
        ResultSet resultSet = statement.executeQuery();
        this.resultSet = new EncryptResultSet(this, resultSet, connection.getEncryptRule());
        return resultSet;
    }
    
    private String getRewriteSQL(final String sql) {
        SQLStatement sqlStatement = connection.getEncryptSQLParsingEngine().parse(false, sql);
        OptimizeEngineFactory.newInstance(connection.getEncryptRule(), sqlStatement, new LinkedList<>()).optimize();
        SQLBuilder sqlBuilder = new EncryptSQLRewriteEngine(connection.getEncryptRule(), sql, connection.getDatabaseType(), sqlStatement, new LinkedList<>()).rewrite();
        return sqlBuilder.toSQL().getSql();
    }
    
    @Override
    public ResultSet getResultSet() {
        return resultSet;
    }
    
    @Override
    public int executeUpdate() throws SQLException {
        int result = statement.executeUpdate();
        clearBatch();
        return result;
    }
    
    @Override
    public boolean execute() throws SQLException {
        boolean result = statement.execute();
        clearBatch();
        return result;
    }
    
    @Override
    public ResultSet getGeneratedKeys() throws SQLException {
        return statement.getGeneratedKeys();
    }
    
    @Override
    public void addBatch() throws SQLException {
        statement.addBatch();
        
    }
    
    @Override
    public void clearBatch() {
        resultSet = null;
        clearParameters();
    }
    
    @RequiredArgsConstructor
    private final class EncryptPreparedStatementGenerator {
    
        private final EncryptConnection connection;
    
        private final int resultSetType;
    
        private final int resultSetConcurrency;
    
        private final int resultSetHoldability;
    
        private final int autoGeneratedKeys;
    
        private final int[] columnIndexes;
    
        private final String[] columnNames;
        
        private EncryptPreparedStatementGenerator(final EncryptConnection connection) {
            this(connection, -1, -1, -1, -1, null, null);
        }
        
        private EncryptPreparedStatementGenerator(final EncryptConnection connection, final int resultSetType, final int resultSetConcurrency) {
            this(connection, resultSetType, resultSetConcurrency, -1, -1, null, null);
        }
    
        private EncryptPreparedStatementGenerator(final EncryptConnection connection, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) {
            this(connection, resultSetType, resultSetConcurrency, resultSetHoldability, -1, null, null);
        }
    
        private EncryptPreparedStatementGenerator(final EncryptConnection connection, final int autoGeneratedKeys) {
            this(connection, -1, -1, -1, autoGeneratedKeys, null, null);
        }
    
        private EncryptPreparedStatementGenerator(final EncryptConnection connection, final int[] columnIndexes) {
            this(connection, -1, -1, -1, -1, columnIndexes, null);
        }
    
        private EncryptPreparedStatementGenerator(final EncryptConnection connection, final String[] columnNames) {
            this(connection, -1, -1, -1, -1, null, columnNames);
        }
        
        private PreparedStatement createEncryptPreparedStatement(final String sql) {
            if (-1 != resultSetType && -1 != resultSetConcurrency && -1 != resultSetHoldability) {
                return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
            }
        }
    }
}

@@ -1862,24 +1862,25 @@
 tatement
-MetaData
+Generator
 ;%0A    %0A 
@@ -2083,32 +2083,33 @@
 redStatement
-MetaData
+Generator
  = new Encry
@@ -2137,16 +2137,26 @@
 nerator(
+connection
 );%0A    %7D
@@ -2332,46 +2332,8 @@
 ) %7B%0A
-        this.connection = connection;%0A
     
@@ -2373,32 +2373,33 @@
 redStatement
-MetaData
+Generator
  = new Encry
@@ -2419,32 +2419,44 @@
 tementGenerator(
+connection, 
 resultSetType, r
@@ -2691,46 +2691,8 @@
 ) %7B%0A
-        this.connection = connection;%0A
     
@@ -2732,32 +2732,33 @@
 redStatement
-MetaData
+Generator
  = new Encry
@@ -2786,16 +2786,28 @@
 nerator(
+connection, 
 resultSe
@@ -3012,46 +3012,8 @@
 ) %7B%0A
-        this.connection = connection;%0A
     
@@ -3053,32 +3053,33 @@
 redStatement
-MetaData
+Generator
  = new Encry
@@ -3107,16 +3107,28 @@
 nerator(
+connection, 
 autoGene
@@ -3291,46 +3291,8 @@
 ) %7B%0A
-        this.connection = connection;%0A
     
@@ -3332,32 +3332,33 @@
 redStatement
-MetaData
+Generator
  = new Encry
@@ -3382,24 +3382,36 @@
 ntGenerator(
+connection, 
 columnIndexe
@@ -3567,46 +3567,8 @@
 ) %7B%0A
-        this.connection = connection;%0A
     
@@ -3616,16 +3616,17 @@
 ment
-MetaData
+Generator
  = n
@@ -3662,16 +3662,28 @@
 nerator(
+connection, 
 columnNa

use preparedStatementGenerator