package picker

import "math/rand"

type Picker struct {
	n       int
	intn    func(int) int
	options []int
}

func New(n int, intn func(int) int) *Picker {
	if intn == nil {
		intn = rand.Intn
	}
	p := &Picker{n: n, intn: intn, options: make([]int, n)}
	for i := range p.options {
		// TODO: avoid this overhead, store only replacements
		p.options[i] = i
	}
	return p
}

func (p *Picker) Pick() int {
	n := len(p.options)
	if n < 1 {
		return -1
	}
	i := p.intn(n)

	p.options[i], p.options[n-1] = p.options[n-1], p.options[i]

	choice := p.options[n-1]
	p.options = p.options[:n-1]

	return choice
}

func (p *Picker) Replace(choice int) {
	if choice < 0 {
		return
	}
	p.options = append(p.options, choice)
}
