/*
 * 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.SneakyThrows;
import org.apache.shardingsphere.core.optimize.OptimizeEngineFactory;
import org.apache.shardingsphere.core.optimize.result.OptimizeResult;
import org.apache.shardingsphere.core.parse.parser.sql.SQLStatement;
import org.apache.shardingsphere.core.rewrite.EncryptSQLRewriteEngine;
import org.apache.shardingsphere.core.rewrite.SQLBuilder;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.connection.EncryptConnection;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset.EncryptResultSet;
import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationStatement;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.LinkedList;

/**
 * Encrypt statement.
 *
 * @author panjuan
 */
public final class EncryptStatement extends AbstractUnsupportedOperationStatement {
    
    private final Statement statement;
    
    private final EncryptConnection connection;
    
    private EncryptResultSet resultSet;
    
    @SneakyThrows
    public EncryptStatement(final EncryptConnection connection) {
        statement = connection.getConnection().createStatement();
        this.connection = connection;
    }
    
    @SneakyThrows
    public EncryptStatement(final EncryptConnection connection, final int resultSetType, final int resultSetConcurrency) {
        statement = connection.getConnection().createStatement(resultSetType, resultSetConcurrency);
        this.connection = connection;
    }
    
    @SneakyThrows
    public EncryptStatement(final EncryptConnection connection, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) {
        statement = connection.getConnection().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
        this.connection = connection;
    }
    
    @Override
    public ResultSet executeQuery(final String sql) throws SQLException {
        ResultSet resultSet = statement.executeQuery(getRewriteSQL(sql));
        this.resultSet = new EncryptResultSet(this, resultSet, connection.getEncryptRule());
        return resultSet;
    }
    
    @Override
    public ResultSet getResultSet() {
        return resultSet;
    }
    
    private String getRewriteSQL(final String sql) {
        SQLStatement sqlStatement = connection.getEncryptSQLParsingEngine().parse(false, sql);
        OptimizeResult optimizeResult = OptimizeEngineFactory.newInstance(connection.getEncryptRule(), sqlStatement, new LinkedList<>()).optimize();
        SQLBuilder sqlBuilder = new EncryptSQLRewriteEngine(connection.getEncryptRule(), sql, connection.getDatabaseType(), sqlStatement, new LinkedList<>(), optimizeResult).rewrite();
        return sqlBuilder.toSQL().getSql();
    }
    
    @Override
    public int executeUpdate(final String sql) throws SQLException {
        return statement.executeUpdate(getRewriteSQL(sql));
    }
    
    @Override
    public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException {
        return statement.executeUpdate(getRewriteSQL(sql), autoGeneratedKeys);
    }
    
    @Override
    public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException {
        return statement.executeUpdate(getRewriteSQL(sql), columnIndexes);
    }
    
    @Override
    public int executeUpdate(final String sql, final String[] columnNames) throws SQLException {
        return statement.executeUpdate(getRewriteSQL(sql), columnNames);
    }
    
    @Override
    public boolean execute(final String sql) throws SQLException {
        boolean result = statement.execute(getRewriteSQL(sql));
        this.resultSet = createEncryptResultSet(statement);
        return result;
    }
    
    @Override
    public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException {
        boolean result = statement.execute(getRewriteSQL(sql), autoGeneratedKeys);
        this.resultSet = createEncryptResultSet(statement);
        return result;
    }
    
    @Override
    public boolean execute(final String sql, final int[] columnIndexes) throws SQLException {
        boolean result = statement.execute(getRewriteSQL(sql), columnIndexes);
        this.resultSet = createEncryptResultSet(statement);
        return result;
    }
    
    @Override
    public boolean execute(final String sql, final String[] columnNames) throws SQLException {
        boolean result = statement.execute(getRewriteSQL(sql), columnNames);
        this.resultSet = createEncryptResultSet(statement);
        return result;
    }
    
    private EncryptResultSet createEncryptResultSet(final Statement statement) throws SQLException {
        return null == statement.getResultSet() ? null : new EncryptResultSet(this, statement.getResultSet(), connection.getEncryptRule());
    }
    
    @Override
    public void close() throws SQLException {
        statement.close();
    }
    
    @Override
    public int getMaxFieldSize() throws SQLException {
        return statement.getMaxFieldSize();
    }
    
    @Override
    public void setMaxFieldSize(final int max) throws SQLException {
        statement.setMaxFieldSize(max);
    }
    
    @Override
    public int getMaxRows() throws SQLException {
        return statement.getMaxRows();
    }
    
    @Override
    public void setMaxRows(final int max) throws SQLException {
        statement.setMaxRows(max);
    }
    
    @Override
    public void setEscapeProcessing(final boolean enable) throws SQLException {
        statement.setEscapeProcessing(enable);
    }
    
    @Override
    public int getQueryTimeout() throws SQLException {
        return statement.getQueryTimeout();
    }
    
    @Override
    public void setQueryTimeout(final int seconds) throws SQLException {
        statement.setQueryTimeout(seconds);
    }
    
    @Override
    public void cancel() throws SQLException {
        statement.cancel();
    }
    
    @Override
    public SQLWarning getWarnings() throws SQLException {
        return statement.getWarnings();
    }
    
    @Override
    public void clearWarnings() throws SQLException {
        statement.clearWarnings();
    }
    
    @Override
    public int getUpdateCount() throws SQLException {
        return statement.getUpdateCount();
    }
    
    @Override
    public boolean getMoreResults() throws SQLException {
        return statement.getMoreResults();
    }
    
    @Override
    public boolean getMoreResults(final int current) throws SQLException {
        return statement.getMoreResults(current);
    }
    
    @Override
    public void setFetchSize(final int rows) throws SQLException {
        statement.setFetchSize(rows);
    }
    
    @Override
    public int getFetchSize() throws SQLException {
        return statement.getFetchSize();
    }
    
    @Override
    public int getResultSetConcurrency() throws SQLException {
        return statement.getResultSetConcurrency();
    }
    
    @Override
    public int getResultSetType() throws SQLException {
        return statement.getResultSetType();
    }
    
    @Override
    public Connection getConnection() {
        return connection;
    }
    
    @Override
    public ResultSet getGeneratedKeys() throws SQLException {
        return statement.getGeneratedKeys();
    }
    
    @Override
    public int getResultSetHoldability() throws SQLException {
        return statement.getResultSetHoldability();
    }
    
    @Override
    public boolean isClosed() throws SQLException {
        return statement.isClosed();
    }
    
    @Override
    public void setPoolable(final boolean poolable) throws SQLException {
        statement.setPoolable(poolable);
    }
    
    @Override
    public boolean isPoolable() throws SQLException {
        return statement.isPoolable();
    }
}

@@ -3054,32 +3054,37 @@
 %0A        return 
+this.
 resultSet;%0A    %7D

return this.resultSet