package com.jscape.util.io.primitive;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * @author Alex Usun
 */
public class ShortStringCodec
        implements DataCodec<String> {

    private final EndianBits bits;
    private final Charset charset;

    public static void writeValue(String value, EndianBits bits, Charset charset, OutputStream out)
            throws IOException {
        ShortByteArrayCodec.writeValue(value.getBytes(charset), bits, out);
    }

    public static void writeBigEndianValue(String value, Charset charset, OutputStream out)
            throws IOException {
        ShortByteArrayCodec.writeBigEndianValue(value.getBytes(charset), out);
    }

    public static void writeLittleEndianValue(String value, Charset charset, OutputStream out)
            throws IOException {
        ShortByteArrayCodec.writeLittleEndianValue(value.getBytes(charset), out);
    }

    public static String readValue(EndianBits bits, Charset charset, InputStream in)
            throws IOException {
        return new String(ShortByteArrayCodec.readValue(bits, in), charset);
    }

    public static String readBigEndianValue(Charset charset, InputStream in)
            throws IOException {
        return new String(ShortByteArrayCodec.readBigEndianValue(in), charset);
    }

    public static String readLittleEndianValue(Charset charset, InputStream in)
            throws IOException {
        return new String(ShortByteArrayCodec.readLittleEndianValue(in), charset);
    }

    public ShortStringCodec(EndianBits bits, Charset charset) {
        this.bits = bits;
        this.charset = charset;
    }

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

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

}