package com.jscape.inet.ftp;

import com.jscape.crypto.Hash;

import java.io.InputStream;

/**
 * @author Alex Usun
 */
public enum Checksum {

    CRC32("crc32") {
        @Override
        protected Hash hash()
                throws Exception {
            return com.jscape.crypto.CRC32.bigEndianHash();
        }
    },
    MD5("md5") {
        @Override
        protected Hash hash()
                throws Exception {
            return com.jscape.crypto.MD5.defaultHash();
        }
    };

    private static final int BUFFER_SIZE = 8192;

    public final String code;

    Checksum(String code) {
        this.code = code;
    }

    public byte[] of(InputStream in, long length)
            throws Exception {
        Hash hash = hash();
        return of(in, length, hash);
    }

    protected abstract Hash hash()
            throws Exception;

    protected byte[] of(InputStream in, long totalLength, Hash hash)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        int read;
        int length = (int) Math.min(buf.length, totalLength);

        while ((read = in.read(buf, 0, length)) != -1 && totalLength > 0) {
            totalLength -= read;
            hash.update(buf, 0, read);
            length = (int) Math.min(buf.length, totalLength);
        }

        return hash.compute();
    }
}
