
// blake3 provides functions to hash bytes with the blake3 hash function

package blake3

import "seekia/internal/encoding"

import zeeboBlake3 "github.com/zeebo/blake3"

import "errors"


func GetBlake3HashAsBytes(hashLengthBytes int, data []byte)([]byte, error){

	if (hashLengthBytes < 1 || hashLengthBytes > 64){
		return nil, errors.New("GetBlake3HashAsBytes called with invalid blake3 hash length.")
	}
	if (len(data) == 0){
		return nil, errors.New("GetBlake3HashAsBytes called with empty bytes.")
	}

	hasher := zeeboBlake3.New()
	hasher.Write(data)

	digestObject := hasher.Digest()

	output := make([]byte, hashLengthBytes)
	
	_, err := digestObject.Read(output)
	if (err != nil) { return nil, err }

	return output, nil
}

func Get32ByteBlake3Hash(data []byte)([32]byte, error){

	if (len(data) == 0){
		return [32]byte{}, errors.New("Get32ByteBlake3Hash called with empty bytes.")
	}

	result := zeeboBlake3.Sum256(data)

	return result, nil
}

func GetBlake3HashAsHexString(hashLengthBytes int, data []byte)(string, error){

	hashResult, err := GetBlake3HashAsBytes(hashLengthBytes, data)
	if (err != nil) { return "", err }

	result := encoding.EncodeBytesToHexString(hashResult[:])

	return result, nil
}

func GetBlake3HashAsBase32String(hashLengthBytes int, data []byte)(string, error){

	remainder := hashLengthBytes % 5
	if (remainder != 0){
		return "", errors.New("GetBlake3HashAsBase32String called with invalid hash length.")
	}

	hashResult, err := GetBlake3HashAsBytes(hashLengthBytes, data)
	if (err != nil) { return "", err }
	
	base32Result := encoding.EncodeBytesToBase32String(hashResult)

	return base32Result, nil
}



