/*
 * 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.polaris.persistence.relational.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.polaris.persistence.relational.jdbc.models.Converter;

/**
 * Used to wrap a ResultSet and to build a stream from the data it contains. This data structure
 * will not close the ResultSet passed in, so the caller is still responsible for managing its
 * lifecycle
 */
public class ResultSetIterator<T> implements Iterator<T> {
  private final ResultSet resultSet;
  private final Converter<T> converterInstance;
  private boolean hasNext;

  public ResultSetIterator(ResultSet resultSet, Converter<T> converterInstance)
      throws SQLException {
    this.resultSet = resultSet;
    this.converterInstance = converterInstance;
    advance();
  }

  private void advance() throws SQLException {
    try {
      hasNext = resultSet.next();
    } catch (SQLException e) {
      hasNext = false;
      throw e;
    }
  }

  @Override
  public boolean hasNext() {
    return hasNext;
  }

  @Override
  public T next() {
    if (!hasNext) {
      throw new NoSuchElementException();
    }
    try {
      T object = converterInstance.fromResultSet(resultSet);
      advance();
      return object;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public Stream<T> toStream() {
    Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(this, 0);
    return StreamSupport.stream(spliterator, false);
  }
}
