package com.capgemini.framework.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.sql.Statement;

/**
 * Class for all JDBC connections.
 */
public class DbManager {
  private static final Logger log = LoggerFactory.getLogger(DbManager.class);
  private final DbConnection connection;

  public DbManager(final String url, final String login, final String password) {
    connection = new DbConnection(url, login, password);
  }

  /**
   * Execute a query for private use of this utility class.
   *
   * @param query the SQL query
   * @return the number of affected rows
   */
  private int execute(final String query) throws SQLException {
    try (Statement theStatement = connection.getConnection().createStatement()) {
      return theStatement.executeUpdate(query);
    }
  }

  /**
   * Execute a SQL query with stack trace display parameter.
   *
   * @param aQuery SQL query content.
   * @return True when the query has been executed successfully.
   */
  boolean executeQuery(final String aQuery) {
    boolean status = true;
    int nbRowsImpacted = executeQueryAndGetRowCount(aQuery);
    if (nbRowsImpacted < 0) {
      status = false;
    }
    return status;
  }

  /**
   * Execute a SQL query and findAll its impacted rows count (for UPDATE and DELETE operations).
   *
   * @param aQuery SQL query content.
   * @return impacted row count (-1 = error).
   */
  private int executeQueryAndGetRowCount(final String aQuery) {
    try {
      return execute(aQuery);
    }
    catch (SQLException e) {
      if (!isIgnoredError(e)) {
        log.error("SQL error detected during following query execution: " + aQuery, e);
      }
      return -1;
    }
  }

  private boolean isIgnoredError(final SQLException exc) {
    int theErrorCode = exc.getErrorCode();
    return theErrorCode == 2289 || theErrorCode == 942;
  }
}
