package qos

import (
	"context"
	"errors"

	qosSemaphore "git.frostfs.info/TrueCloudLab/frostfs-qos/limiting/semaphore"
	"git.frostfs.info/TrueCloudLab/frostfs-qos/scheduling"
)

var (
	_                         scheduler = (*semaphore)(nil)
	errSemaphoreLimitExceeded           = errors.New("semaphore limit exceeded")
)

type semaphore struct {
	s *qosSemaphore.Semaphore
}

func newSemaphoreScheduler(size int64) *semaphore {
	return &semaphore{
		s: qosSemaphore.NewSemaphore(size),
	}
}

func (s *semaphore) Close() {}

func (s *semaphore) RequestArrival(ctx context.Context, _ string) (scheduling.ReleaseFunc, error) {
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
	}

	if s.s.Acquire() {
		return s.s.Release, nil
	}
	return nil, errSemaphoreLimitExceeded
}