/*
 *  @author Ranides Atterwim {@literal <ranides@gmail.com>}
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */

package net.ranides.assira.io;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import net.ranides.assira.text.Charsets;

/**
 * Extension of ByteArrayOutputStream.
 * It converts stored binary data into string using provided charset
 *
 * @author ranides
 */
public class StringOutput extends ByteArrayOutputStream {
    
    private final Charset cs;

    /**
     * Creates new stream using UTF8 charset as default
     */
    public StringOutput() {
        this(Charsets.UTF8);
    }


    /**
     * Creates new stream using provided charset as default
     *
     * @param cs cs
     */
    public StringOutput(Charset cs) {
        super();
        this.cs = cs;
    }

    /**
     * Decodes buffer's contents into String using stream's default charset.
     *
     * @return String
     */
    @Override
    public String toString() {
        return toString(cs);
    }

    /**
     * Decodes buffer's contents into String using provided charset.
     *
     * @return String
     */
    @Override
    public String toString(String charset) throws UnsupportedCharsetException {
        try {
            return super.toString(charset);
        } catch (UnsupportedEncodingException cause) {
            throw new UnsupportedCharsetException(charset);
        }
    }

    /**
     * Decodes buffer's contents into String using provided charset.
     *
     * @param charset charset
     * @return String
     */
    public String toString(Charset charset) {
        return toString(charset.name());
    }

    /**
     * Default charset used by {@link #toString()} method.
     * It is configured at creation time.
     * It is UTF8 if not defined explicitly.
     *
     * @return charset
     */
    public Charset charset() {
        return cs;
    }
    
}