package drng

import (
	"bytes"
	"math"

	"xdx.jelly/xgcl/grand/drng/entropy"
	"xdx.jelly/xgcl/grand/drng/internal"
)

const ALPHA = 9.5367431640625e-07 // = 2^(-20)

func next(source entropy.EntropySource) []byte {
	b, err := source.GetEntropy(internal.MinEntropyInputLength, internal.MinEntropyInputLength, internal.MaxEntropyInputLength)
	if err != nil {
		return nil
	}
	return b
}

// 连续健康测试
func RepeatCounterHealthyTests(source entropy.EntropySource, n int, H int) bool {
	C := 1 + int64(math.Ceil(-math.Log2(ALPHA)/float64(H)))
	A := next(source)
	if A == nil {
		return false
	}
	B := int64(1)
	for i := 0; i < n; i++ {
		X := next(source)
		if X == nil {
			return false
		}
		if bytes.Equal(X, A) {
			B++
		}
		if B >= C {
			return false
		} else {
			A = X
			B = 1
		}
	}
	return true
}
