package worker

import (
	"fmt"
)

type Pool struct {
	limit   int
	workers chan *Worker
}

type Worker struct {
	ID string
}

func NewPool(limit int, name string) *Pool {
	if limit <= 0 {
		limit = 1
	}
	workers := make(chan *Worker, limit)
	for i := 0; i < limit; i++ {
		workers <- &Worker{ID: fmt.Sprintf("%s-%d", name, int64(i+1))}
	}

	return &Pool{
		limit:   limit,
		workers: workers,
	}
}

func (pool *Pool) Apply() *Worker {
	worker := <-pool.workers
	return worker
}

func (pool *Pool) Recycle(worker *Worker) {
	if worker == nil {
		panic("invalid restore worker")
	}
	pool.workers <- worker
}

func (pool *Pool) HasWorker() bool {
	return len(pool.workers) > 0
}
