/*
 * Copyright (c) 2011-2014 The original author or authors
 * ------------------------------------------------------
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Apache License v2.0 which accompanies this distribution.
 *
 *     The Eclipse Public License is available at
 *     http://www.eclipse.org/legal/epl-v10.html
 *
 *     The Apache License v2.0 is available at
 *     http://www.opensource.org/licenses/apache2.0.php
 *
 * You may elect to redistribute this code under either of these licenses.
 */

package io.vertx.ext.jdbc.impl.actions;

import io.vertx.core.Context;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.UpdateResult;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Pattern;

import static io.vertx.ext.jdbc.impl.actions.JDBCStatementHelper.*;

/**
 * @author <a href="mailto:nscavell@redhat.com">Nick Scavelli</a>
 */
public class JDBCUpdate extends AbstractJDBCAction<UpdateResult> {

  private static final Pattern regex = Pattern.compile(".*insert.*", Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);

  private final String sql;
  private final JsonArray in;

  public JDBCUpdate(Vertx vertx, Connection connection, Context context, String sql, JsonArray in) {
    super(vertx, connection, context);
    this.sql = sql;
    this.in = in;
  }

  @Override
  protected UpdateResult execute(Connection conn) throws SQLException {
    final boolean returKeys = regex.matcher(sql).matches();
    try (PreparedStatement statement = conn.prepareStatement(sql, returKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS)) {
      fillStatement(statement, in);

      int updated = statement.executeUpdate();
      JsonArray keys = new JsonArray();

      // Create JsonArray of keys
      if (returKeys) {
        try (ResultSet rs = statement.getGeneratedKeys()) {
          if (rs != null) {
            while (rs.next()) {
              Object key = rs.getObject(1);
              if (key != null) {
                keys.add(convertSqlValue(key));
              }
            }
          }
        } catch (SQLException e) {
          // do not crash if no permissions
        }
      }

      return new UpdateResult(updated, keys);
    }
  }

  @Override
  protected String name() {
    return "update";
  }
}

@@ -1234,18 +1234,28 @@
 le(%22
-.*insert.*
+(%5E%7C%5C%5Cs)insert(%5C%5Cs%7C$)
 %22, P
@@ -1680,17 +1680,25 @@
 ql).
-matches()
+groupCount() == 2
 ;%0A  

update regex to match exactly the insert keyword, not tokens like "inserted"