/*
 * Adapted from The MIT License (MIT)
 *
 * Copyright (c) 2018-2020 DaPorkchop_
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
 * is furnished to do so, subject to the following conditions:
 *
 * Any persons and/or organizations using this software must include the above copyright notice and this permission notice,
 * provide sufficient credit to the original authors of the project (IE: DaPorkchop_), as well as provide a link to the original project.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

package net.daporkchop.lib.hash.alg.base;

import lombok.NonNull;
import net.daporkchop.lib.binary.util.Pack;
import net.daporkchop.lib.hash.util.DigestAlg;

/**
 * Base class for SHA-512
 *
 * @author Some BouncyCastle dev
 */
public abstract class LongDigest implements DigestAlg {
    private static final int BYTE_LENGTH = 128;
    private static final long K[] = {
            0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL,
            0x3956c25bf348b538L, 0x59f111f1b605d019L, 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L,
            0xd807aa98a3030242L, 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
            0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L, 0xc19bf174cf692694L,
            0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L, 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L,
            0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
            0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L,
            0xc6e00bf33da88fc2L, 0xd5a79147930aa725L, 0x06ca6351e003826fL, 0x142929670a0e6e70L,
            0x27b70a8546d22ffcL, 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
            0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L, 0x92722c851482353bL,
            0xa2bfe8a14cf10364L, 0xa81a664bbc423001L, 0xc24b8b70d0f89791L, 0xc76c51a30654be30L,
            0xd192e819d6ef5218L, 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
            0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L,
            0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL, 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L,
            0x748f82ee5defb2fcL, 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
            0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL,
            0xca273eceea26619cL, 0xd186b8c721c0c207L, 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L,
            0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL,
            0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL,
            0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL, 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L
    };
    private final byte[] xBuf = new byte[8];
    private int xBufOff;
    private long byteCount1;
    private long byteCount2;
    protected long H1;
    protected long H2;
    protected long H3;
    protected long H4;
    protected long H5;
    protected long H6;
    protected long H7;
    protected long H8;
    private final long[] W = new long[80];
    private int wOff;

    protected LongDigest() {
        this.xBufOff = 0;

        this.reset();
    }

    public void update(byte in) {
        this.xBuf[this.xBufOff++] = in;

        if (this.xBufOff == this.xBuf.length) {
            this.processWord(this.xBuf, 0);
            this.xBufOff = 0;
        }

        this.byteCount1++;
    }

    @Override
    public void update(@NonNull byte[] in, int inOff, int len) {
        //
        // fill the current word
        //
        while ((this.xBufOff != 0) && (len > 0)) {
            this.update(in[inOff]);

            inOff++;
            len--;
        }

        //
        // process whole words.
        //
        while (len > this.xBuf.length) {
            this.processWord(in, inOff);

            inOff += this.xBuf.length;
            len -= this.xBuf.length;
            this.byteCount1 = (long) (this.byteCount1 + this.xBuf.length);
        }

        //
        // load in the remainder.
        //
        while (len > 0) {
            this.update(in[inOff]);

            inOff++;
            len--;
        }
    }

    public void finish() {
        this.adjustByteCounts();

        long lowBitLength = this.byteCount1 << 3;
        long hiBitLength = this.byteCount2;

        //
        // add the pad bytes.
        //
        this.update((byte) 128);

        while (this.xBufOff != 0) {
            this.update((byte) 0);
        }

        this.processLength(lowBitLength, hiBitLength);

        this.processBlock();
    }

    @Override
    public void reset() {
        this.byteCount1 = 0L;
        this.byteCount2 = 0L;

        this.xBufOff = 0;
        for (int i = 0; i < this.xBuf.length; i++) {
            this.xBuf[i] = (byte) 0;
        }

        this.wOff = 0;
        for (int i = 0; i != this.W.length; i++) {
            this.W[i] = 0L;
        }
    }

    @Override
    public int getInternalBufferSize() {
        return BYTE_LENGTH;
    }

    protected void processWord(@NonNull byte[] in, int inOff) {
        this.W[this.wOff] = Pack.bigEndianToLong(in, inOff);

        if (++this.wOff == 16) {
            this.processBlock();
        }
    }

    private void adjustByteCounts() {
        if (this.byteCount1 > 0x1fffffffffffffffL) {
            this.byteCount2 += (this.byteCount1 >>> 61);
            this.byteCount1 &= 0x1fffffffffffffffL;
        }
    }

    protected void processLength(long lowW, long hiW) {
        if (this.wOff > 14) {
            this.processBlock();
        }

        this.W[14] = hiW;
        this.W[15] = lowW;
    }

    protected void processBlock() {
        this.adjustByteCounts();

        // expand 16 word block into 80 word blocks.
        for (int t = 16; t <= 79; t++) {
            this.W[t] = this.Sigma1(this.W[t - 2]) + this.W[t - 7] + this.Sigma0(this.W[t - 15]) + this.W[t - 16];
        }

        // set up working variables.
        long a = this.H1;
        long b = this.H2;
        long c = this.H3;
        long d = this.H4;
        long e = this.H5;
        long f = this.H6;
        long g = this.H7;
        long h = this.H8;

        int t = 0;
        for (int i = 0; i < 10; i++) {
            // t = 8 * i
            h += this.Sum1(e) + this.Ch(e, f, g) + K[t] + this.W[t++];
            d += h;
            h += this.Sum0(a) + this.Maj(a, b, c);

            // t = 8 * i + 1
            g += this.Sum1(d) + this.Ch(d, e, f) + K[t] + this.W[t++];
            c += g;
            g += this.Sum0(h) + this.Maj(h, a, b);

            // t = 8 * i + 2
            f += this.Sum1(c) + this.Ch(c, d, e) + K[t] + this.W[t++];
            b += f;
            f += this.Sum0(g) + this.Maj(g, h, a);

            // t = 8 * i + 3
            e += this.Sum1(b) + this.Ch(b, c, d) + K[t] + this.W[t++];
            a += e;
            e += this.Sum0(f) + this.Maj(f, g, h);

            // t = 8 * i + 4
            d += this.Sum1(a) + this.Ch(a, b, c) + K[t] + this.W[t++];
            h += d;
            d += this.Sum0(e) + this.Maj(e, f, g);

            // t = 8 * i + 5
            c += this.Sum1(h) + this.Ch(h, a, b) + K[t] + this.W[t++];
            g += c;
            c += this.Sum0(d) + this.Maj(d, e, f);

            // t = 8 * i + 6
            b += this.Sum1(g) + this.Ch(g, h, a) + K[t] + this.W[t++];
            f += b;
            b += this.Sum0(c) + this.Maj(c, d, e);

            // t = 8 * i + 7
            a += this.Sum1(f) + this.Ch(f, g, h) + K[t] + this.W[t++];
            e += a;
            a += this.Sum0(b) + this.Maj(b, c, d);
        }

        this.H1 += a;
        this.H2 += b;
        this.H3 += c;
        this.H4 += d;
        this.H5 += e;
        this.H6 += f;
        this.H7 += g;
        this.H8 += h;

        // reset the offset and clean out the word buffer.
        this.wOff = 0;
        for (int i = 0; i < 16; i++) {
            this.W[i] = 0L;
        }
    }

    private long Ch(long x, long y, long z) {
        return ((x & y) ^ ((~x) & z));
    }

    private long Maj(long x, long y, long z) {
        return ((x & y) ^ (x & z) ^ (y & z));
    }

    private long Sum0(long x) {
        return ((x << 36) | (x >>> 28)) ^ ((x << 30) | (x >>> 34)) ^ ((x << 25) | (x >>> 39));
    }

    private long Sum1(long x) {
        return ((x << 50) | (x >>> 14)) ^ ((x << 46) | (x >>> 18)) ^ ((x << 23) | (x >>> 41));
    }

    private long Sigma0(long x) {
        return ((x << 63) | (x >>> 1)) ^ ((x << 56) | (x >>> 8)) ^ (x >>> 7);
    }

    private long Sigma1(long x) {
        return ((x << 45) | (x >>> 19)) ^ ((x << 3) | (x >>> 61)) ^ (x >>> 6);
    }
}
