/*
 * 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.jena.tdb2.xloader;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.jena.atlas.AtlasException;
import org.apache.jena.atlas.lib.Hex;

/** Buffered writer of rows of longs, in hex. */
class WriteRows
{
    private OutputStream output;
    boolean atStartOfRow = true;
    private int itemsPerRow;
    private int rowBlock;
    private byte[] b;
    private int idx;
    private int rows;
    private int rowLength;

    WriteRows(OutputStream output, int itemsPerRow, int rowBlock) {
        this.output = output;
        this.itemsPerRow = itemsPerRow;
        this.rowLength = 16 * itemsPerRow + itemsPerRow;
        this.rowBlock = rowBlock;
        // Does it's own buffering in exact rows.
        // BufferedOutputStream uses synchronized.
        this.b = new byte[rowLength * rowBlock];
        this.idx = 0;
        this.rows = 0;
    }

    public void write(long value) {
        if ( !atStartOfRow ) {
            b[idx] = ' ';
            idx++;
        } else
            atStartOfRow = false;
        Hex.formatUnsignedLongHex(b, idx, value, 16);
        idx += 16;
    }

    public void endOfRow() {
        b[idx] = '\n';
        idx++;
        atStartOfRow = true;
        rows++;
        if ( rows == rowBlock )
            flush();
    }

    public void flush() {
        try {
            output.write(b, 0, rows * rowLength);
        } catch (IOException e) {
            throw new AtlasException(e);
        }
        idx = 0;
        rows = 0;
    }

    public void close() {
        flush();
        try {
            output.flush();
        } catch (IOException e) {
            throw new AtlasException(e);
        }
    }
}
