package util

import "context"

type SimpleWorkerPool struct {
	pool chan struct{}
}

func NewSimpleWorkerPool(size int) *SimpleWorkerPool {
	pool := make(chan struct{}, size)
	for i := 0; i < size; i++ {
		pool <- struct{}{}
	}
	threadPool := &SimpleWorkerPool{
		pool: pool,
	}
	return threadPool
}

func (t *SimpleWorkerPool) Apply(ctx context.Context, fn func(context.Context)) {
	select {
	case <-ctx.Done():
		return
	case <-t.pool:
		go t.runFn(ctx, fn)
	}
}

func (t *SimpleWorkerPool) runFn(ctx context.Context, fn func(context.Context)) {
	defer func() {
		t.pool <- struct{}{}
	}()

	fn(ctx)
}
