/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.codec.digest;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

/**
 * Tests {@link MessageDigestAlgorithms}.
 */
class MessageDigestAlgorithmsTest {

    @BeforeAll
    static void checkValues() throws Exception {
        final Field[] fields = MessageDigestAlgorithms.class.getDeclaredFields();
        boolean ok = true;
        int psf = 0;
        for (final Field field : fields) {
            // Ignore Cobertura instrumentation fields
            final String name = field.getName();
            if (name.contains("cobertura")) {
                continue;
            }
            // Only interested in public fields
            final int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
                psf++;
                // SHAKE128_256 and SHAKE128_512 are only in Java 25 and up.
                if (!contains((String) field.get(null))) {
                    System.out.printf(
                            "Not found in MessageDigestAlgorithms.values(): %s; note that SHAKE128_256 and SHAKE128_512 are only on Java 25 and up.%n", name);
                    ok = false;
                }
            }
        }
        if (!ok) {
            // SHAKE128_256 and SHAKE128_512 are only in Java 25 and up.
            fail("One or more entries are missing from the MessageDigestAlgorithms.values() array");
        }
        if (psf != MessageDigestAlgorithms.values().length) {
            // SHAKE128_256 and SHAKE128_512 are only in Java 25 and up.
            fail("One or more unexpected entries found in the MessageDigestAlgorithms.values() array");
        }
    }

    private static boolean contains(final String key) {
        for (final String s : MessageDigestAlgorithms.values()) {
            if (s.equals(key)) {
                return true;
            }
        }
        return false;
    }

    static String[] data() {
        return MessageDigestAlgorithms.values();
    }

    private DigestUtilsTest digestUtilsTest;

    private byte[] digestTestData(final String messageDigestAlgorithm) {
        return DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestData());
    }

    private byte[] getTestData() {
        return digestUtilsTest.getTestData();
    }

    private File getTestFile() {
        return digestUtilsTest.getTestPath().toFile();
    }

    private Path getTestPath() {
        return digestUtilsTest.getTestPath();
    }

    private RandomAccessFile getTestRandomAccessFile() {
        return digestUtilsTest.getTestRandomAccessFile();
    }

    @BeforeEach
    void setUp() throws Exception {
        digestUtilsTest = new DigestUtilsTest();
        digestUtilsTest.setUp();
    }

    @AfterEach
    void tearDown() throws Exception {
        digestUtilsTest.tearDown();
        digestUtilsTest = null;
    }

    @ParameterizedTest
    @MethodSource("data")
    void testAlgorithm(final String messageDigestAlgorithm) throws NoSuchAlgorithmException {
        final String algorithm = messageDigestAlgorithm;
        assertNotNull(algorithm);
        assertFalse(algorithm.isEmpty());
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        MessageDigest.getInstance(algorithm);
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestByteArray(final String messageDigestAlgorithm) {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestData()));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestData()));
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestByteBuffer(final String messageDigestAlgorithm) {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        assertArrayEquals(digestTestData(messageDigestAlgorithm),
                DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), ByteBuffer.wrap(getTestData())));
        assertArrayEquals(digestTestData(messageDigestAlgorithm),
                DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), ByteBuffer.wrap(getTestData())));
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestFile(final String messageDigestAlgorithm) throws IOException {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestFile()));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestFile()));
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestInputStream(final String messageDigestAlgorithm) throws IOException {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        assertArrayEquals(digestTestData(messageDigestAlgorithm),
                DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), new ByteArrayInputStream(getTestData())));
        assertArrayEquals(digestTestData(messageDigestAlgorithm),
                DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), new ByteArrayInputStream(getTestData())));
    }

    private void testDigestPath(final String messageDigestAlgorithm, final OpenOption... options) throws IOException {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestPath(), options));
        assertArrayEquals(digestTestData(messageDigestAlgorithm), DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), getTestPath(), options));
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestPathOpenOptionsEmpty(final String messageDigestAlgorithm) throws IOException {
        testDigestPath(messageDigestAlgorithm);
    }

    @ParameterizedTest
    @MethodSource("data")
    void testDigestPathStandardOpenOptionRead(final String messageDigestAlgorithm) throws IOException {
        testDigestPath(messageDigestAlgorithm, StandardOpenOption.READ);
    }

    @ParameterizedTest
    @MethodSource("data")
    void testGetMessageDigest(final String messageDigestAlgorithm) {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));
        final MessageDigest messageDigest = DigestUtils.getDigest(messageDigestAlgorithm);
        assertEquals(messageDigestAlgorithm, messageDigest.getAlgorithm());
    }

    @ParameterizedTest
    @MethodSource("data")
    void testNonBlockingDigestRandomAccessFile(final String messageDigestAlgorithm) throws IOException {
        assumeTrue(DigestUtils.isAvailable(messageDigestAlgorithm));

        final byte[] expected = digestTestData(messageDigestAlgorithm);

        @SuppressWarnings("resource") // test manages RAF
        final RandomAccessFile randomAccessFile = getTestRandomAccessFile();
        assertArrayEquals(expected, DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), randomAccessFile));
        randomAccessFile.seek(0);
        assertArrayEquals(expected, DigestUtils.digest(DigestUtils.getDigest(messageDigestAlgorithm), randomAccessFile));
    }

}
