import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.iceberg.*;
import org.apache.iceberg.deletes.*;
import org.apache.iceberg.io.*;

public class NativeVectors {
  public static PositionDeleteIndex read(Table table, DeleteFile file) throws IOException {
    if (file == null) return PositionDeleteIndex.empty();
    byte[] bytes = new byte[Math.toIntExact(file.contentSizeInBytes())];
    try (SeekableInputStream stream = table.io().newInputFile(file.location()).newStream()) {
      stream.seek(file.contentOffset());
      new java.io.DataInputStream(stream).readFully(bytes);
    }
    return PositionDeleteIndex.deserialize(bytes, file);
  }
  public static DeleteFile write(Table table, DataFile data, DeleteFile previous, long position) throws IOException {
    PositionDeleteIndex old = read(table, previous);
    OutputFileFactory factory = OutputFileFactory.builderFor(table, 0, 0).format(FileFormat.PUFFIN).build();
    BaseDVFileWriter writer = new BaseDVFileWriter(factory, path -> old);
    writer.delete(data.location(), position, table.specs().get(data.specId()), data.partition());
    writer.close();
    return writer.result().deleteFiles().get(0);
  }
  public static List<Long> positions(Table table, DeleteFile file) throws IOException {
    List<Long> positions = new ArrayList<>();
    read(table, file).forEach(positions::add);
    return positions;
  }
}
