package com.atlassian.bitbucket.internal.scm.git.lfs.mirror;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;

import static com.atlassian.bitbucket.internal.scm.git.lfs.mirror.LfsDigestUtils.validate;

public class DigestValidatingInputStream extends DigestInputStream {

    private final String expectedChecksum;
    private final File lfsFile;

    public DigestValidatingInputStream(InputStream delegate, String expectedChecksum, File lfsFile) {
        super(delegate, DigestUtils.getSha256Digest());
        this.expectedChecksum = expectedChecksum;
        this.lfsFile = lfsFile;
    }

    public String getCalculatedChecksum() {
        return Hex.encodeHexString(digest.digest());
    }

    public int read(byte[] b, int off, int len) throws IOException {
        int result = super.read(b, off, len);
        if (result == -1) {
            validate(getCalculatedChecksum(), expectedChecksum, lfsFile);
        }

        return result;
    }

    public int read() throws IOException {
        int ch = super.read();
        if (ch == -1) {
            validate(getCalculatedChecksum(), expectedChecksum, lfsFile);
        }
        return ch;
    }
}
