package jp.sourceforge.shovel.io;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jp.sourceforge.shovel.exception.ApplicationException;

import org.apache.commons.lang.ArrayUtils;

public class ByteBuilder {
    List<Byte> byteList_;
    
    public ByteBuilder() {
        byteList_ = new ArrayList<Byte>();
    }
    
    public void Append(byte val) {
        byteList_.add(val);
    }
    public void Append(byte[] val) {
        if (val != null) {
            Byte[] bytes = ArrayUtils.toObject(val);
            byteList_.addAll(Arrays.asList(bytes));
        }
    }
    public void Append(String val) throws ApplicationException {
        try {
            if (val != null) {
                Append(val.getBytes("UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new ApplicationException("");
        }
    }
    public void Append(int val) {
        Append((short)val);
    }
    public void Append(short val) {
        byteList_.add((byte)((val & 0xff) >> 8));
        byteList_.add((byte)(val & 0xff));
    }
    public byte[] GetBytes() {
        Byte[] bytes = byteList_.toArray(new Byte[byteList_.size()]);
        return ArrayUtils.toPrimitive(bytes);
    }
}
