/*
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (C) 2018 National Library of Australia and the jwarc contributors
 */

package org.netpreserve.jwarc;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

public class WarcWriter {
    private final WritableByteChannel channel;
    private final WarcCompression compression;
    private final ByteBuffer buffer = ByteBuffer.allocate(8192);

    public WarcWriter(WritableByteChannel channel, WarcCompression compression) {
        this.channel = channel;
        this.compression = compression;
    }

    public synchronized void write(WarcRecord record) throws IOException {
        // TODO: buffer headers, compression
        channel.write(ByteBuffer.wrap(record.serializeHeader()));
        MessageBody body = record.body();
        while (body.read(buffer) >= 0) {
            buffer.flip();
            channel.write(buffer);
            buffer.compact();
        }
    }
}

@@ -252,16 +252,63 @@
 Channel;
+%0Aimport java.util.concurrent.atomic.AtomicLong;
 %0A%0Apublic
@@ -490,90 +490,380 @@
 2);%0A
-%0A    public WarcWriter(WritableByteChannel channel, WarcCompression compression) %7B
+    ByteBuffer recordSeperator = ByteBuffer.allocate(2);%0A    %0A    private AtomicLong bytesWritten = new AtomicLong(0);%0A%0A    public WarcWriter(WritableByteChannel channel, WarcCompression compression) %7B%0A        if (compression == WarcCompression.GZIP) %7B%0A            throw new UnsupportedOperationException(%22Writing of GZIP WARC files is not currently supported%22);%0A        %7D
 %0A   
@@ -927,24 +927,88 @@
 ompression;%0A
+        %0A        recordSeperator.put(new byte%5B%5D %7B '%5Cn','%5Cn' %7D);%0A
     %7D%0A%0A    p
@@ -1122,32 +1122,55 @@
 ression%0A        
+bytesWritten.addAndGet(
 channel.write(By
@@ -1209,16 +1209,17 @@
 ader()))
+)
 ;%0A      
@@ -1334,16 +1334,39 @@
         
+bytesWritten.addAndGet(
 channel.
@@ -1378,16 +1378,17 @@
 (buffer)
+)
 ;%0A      
@@ -1417,20 +1417,225 @@
 ;%0A        %7D%0A
+        recordSeperator.rewind();%0A        bytesWritten.addAndGet(channel.write(recordSeperator));%0A                %0A    %7D%0A    %0A    public long getCurrentWritePosition() %7B%0A        return bytesWritten.get();%0A
     %7D%0A%7D%0A

Add required record seperators. Track bytes written.