package throttle

import (
	"bytes"
	"context"
	"io"
	"testing"
	"time"
)

func TestLimiterAverage(t *testing.T) {
	now := time.Unix(0, 0)
	slept := time.Duration(0)
	l := New(100 << 10) // 100 KiB/s
	l.now = func() time.Time { return now }
	l.last = now
	l.sleep = func(_ context.Context, d time.Duration) error {
		slept += d
		now = now.Add(d)
		return nil
	}
	data := bytes.Repeat([]byte("x"), 1<<20) // 1 MiB
	n, err := io.Copy(io.Discard, l.Reader(context.Background(), bytes.NewReader(data)))
	if err != nil || n != 1<<20 {
		t.Fatal(n, err)
	}
	// 1 MiB tegen 100 KiB/s is ruim 10 s, min de eerste burst van 25 KiB.
	if slept < 9500*time.Millisecond || slept > 10500*time.Millisecond {
		t.Fatalf("geslapen %v, verwacht ~10s", slept)
	}
}

func TestUnlimited(t *testing.T) {
	l := New(0)
	r := bytes.NewReader([]byte("abc"))
	if b, _ := io.ReadAll(l.Reader(context.Background(), r)); string(b) != "abc" {
		t.Fatal(string(b))
	}
	if err := l.Wait(context.Background(), 1<<30); err != nil {
		t.Fatal(err)
	}
}

func TestCancel(t *testing.T) {
	l := New(1024)
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	_ = l.Wait(ctx, 16<<10)
	if err := l.Wait(ctx, 16<<10); err == nil {
		t.Fatal("geen fout na annuleren")
	}
}

func TestSetRate(t *testing.T) {
	l := New(0)
	l.SetRate(2048)
	if l.Rate() != 2048 {
		t.Fatal(l.Rate())
	}
	var slept time.Duration
	l.sleep = func(_ context.Context, d time.Duration) error { slept += d; return nil }
	now := time.Unix(0, 0)
	l.now = func() time.Time { return now }
	l.last = now
	l.tokens = 0
	_ = l.Wait(context.Background(), 4096)
	if slept != 2*time.Second {
		t.Fatal(slept)
	}
}
