package com.jscape.util.io.primitive;

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

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

/**
 * @author Alex Usun
 */
public class ShortCodec
        implements DataCodec<Short> {

    private final EndianBits bits;

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

    public static void writeBigEndianValue(short value, OutputStream out)
            throws IOException {
        out.write(value >>> 8);
        out.write(value);
    }

    public static void writeLittleEndianValue(short value, OutputStream out)
            throws IOException {
        out.write(value);
        out.write(value >>> 8);
    }

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

    public static short readBigEndianValue(InputStream in)
            throws IOException {
        int value = IOTools.read(in) << 8;
        value |= IOTools.read(in);

        return (short) value;
    }

    public static short readLittleEndianValue(InputStream in)
            throws IOException {
        int value = IOTools.read(in);
        value |= IOTools.read(in) << 8;

        return (short) value;
    }

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

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

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

}