/*
 * 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.paimon.io;

import org.apache.paimon.data.InternalRow;
import org.apache.paimon.data.columnar.ColumnarRow;
import org.apache.paimon.data.columnar.VectorizedColumnBatch;

import javax.annotation.Nullable;

import java.util.Iterator;
import java.util.NoSuchElementException;

/** {@link BundleRecords} for {@link VectorizedColumnBatch} with optional picked indices. */
public class VectorizedBundleRecords implements BundleRecords {

    private final VectorizedColumnBatch batch;
    @Nullable private final int[] selected;

    public VectorizedBundleRecords(VectorizedColumnBatch batch, @Nullable int[] selected) {
        this.batch = batch;
        this.selected = selected;
    }

    public VectorizedColumnBatch batch() {
        return batch;
    }

    @Nullable
    public int[] selected() {
        return selected;
    }

    @Override
    public long rowCount() {
        return selected != null ? selected.length : batch.getNumRows();
    }

    @Override
    public Iterator<InternalRow> iterator() {
        ColumnarRow row = new ColumnarRow(batch);
        int numRows = selected != null ? selected.length : batch.getNumRows();
        return new Iterator<InternalRow>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < numRows;
            }

            @Override
            public InternalRow next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                row.setRowId(selected != null ? selected[index++] : index++);
                return row;
            }
        };
    }
}
