package info.knacki.pass.io;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OutputStreamWithCheckSum {
    private static final Logger log = Logger.getLogger(OutputStreamWithCheckSum.class.getName());
    private final OutputStream fOutput;
    private MessageDigest fDigest;

    public OutputStreamWithCheckSum(OutputStream out) {
        fOutput = out;
        try {
            fDigest = MessageDigest.getInstance("SHA1");
        }
        catch (NoSuchAlgorithmException e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    public OutputStreamWithCheckSum write(byte []b) throws IOException {
        fDigest.update(b);
        fOutput.write(b);
        return this;
    }

    public OutputStreamWithCheckSum write(String b) throws IOException {
        return write(CharsetHelper.StringToByteArray(b));
    }

    public OutputStreamWithCheckSum writeSha1() throws IOException {
        fOutput.write(fDigest.digest());
        return this;
    }
}
