package com.jscape.util.io.primitive;

import com.jscape.util.BigEndianBits;
import com.jscape.util.EndianBits;
import com.jscape.util.IOTools;
import com.jscape.util.LittleEndianBits;
import com.jscape.util.io.DataCodec;

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

/**
 * @author Alex Usun
 */
public class LongCodec
        implements DataCodec<Long> {

    private final EndianBits bits;

    public static void writeValue(long value, EndianBits bits, OutputStream out)
            throws IOException {
        byte[] data = bits.putLong(value, new byte[8], 0);
        out.write(data);
    }

    public static void writeBigEndianValue(long value, OutputStream out)
            throws IOException {
        writeValue(value, BigEndianBits.INSTANCE, out);
    }

    public static void writeLittleEndianValue(long value, OutputStream out)
            throws IOException {
        writeValue(value, LittleEndianBits.INSTANCE, out);
    }

    public static long readValue(EndianBits bits, InputStream in)
            throws IOException {
        byte[] data = IOTools.read(new byte[8], in);
        return bits.getLong(data, 0);
    }

    public static long readBigEndianValue(InputStream in)
            throws IOException {
        return readValue(BigEndianBits.INSTANCE, in);
    }

    public static long readLittleEndianValue(InputStream in)
            throws IOException {
        return readValue(LittleEndianBits.INSTANCE, in);
    }

    public LongCodec(EndianBits bits) {
        this.bits = bits;
    }

    public void write(Long data, OutputStream out)
            throws IOException {
        writeValue(data, this.bits, out);
    }

    public Long read(InputStream in)
            throws IOException {
        return readValue(this.bits, in);
    }

}