/*
 * Copyright (c) 2011-2021 Contributors to the Eclipse Foundation
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
 * which is available at https://www.apache.org/licenses/LICENSE-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
 */
package io.vertx.oracleclient.impl.commands;

import io.vertx.core.Future;
import io.vertx.core.impl.ContextInternal;
import io.vertx.oracleclient.OraclePrepareOptions;
import io.vertx.oracleclient.impl.Helper;
import io.vertx.sqlclient.Row;
import oracle.jdbc.OraclePreparedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.Flow;
import java.util.stream.Collector;

public class SimpleQueryCommand<C, R> extends QueryCommand<C, R> {

  private final String sql;

  public SimpleQueryCommand(String sql, Collector<Row, C, R> collector) {
    super(collector);
    this.sql = sql;
  }

  @Override
  protected OraclePrepareOptions prepareOptions() {
    return null;
  }

  @Override
  protected boolean returnAutoGeneratedKeys(Connection conn, OraclePrepareOptions options) {
    return false;
  }

  @Override
  protected String query() {
    return sql;
  }

  @Override
  protected void fillStatement(PreparedStatement ps, Connection conn) throws SQLException {
  }

  @Override
  protected Future<OracleResponse<R>> doExecute(OraclePreparedStatement ps, ContextInternal context, boolean returnAutoGeneratedKeys) {
    Flow.Publisher<Boolean> publisher;
    try {
      publisher = ps.executeAsyncOracle();
    } catch (SQLException e) {
      return context.failedFuture(e);
    }
    return Helper.first(publisher, context).compose(returnedResultSet -> {
      return Helper.executeBlocking(context, () -> decode(ps, returnedResultSet, returnAutoGeneratedKeys));
    });
  }
}
