package pool

import (
	"sync"
)

// WorkerPool contains a pool of workers.
// The number of workers in the channel represents how many goruntines
// can be created to execute the task.
// After the task is done, worker will be sent back to the channel.
type WorkerPool struct {
	limit   uint
	workers chan *Worker
	name    string
	wg      sync.WaitGroup
}

// Worker identified by ID.
type Worker struct {
	ID uint64
}

type taskFunc func()

// NewWorkerPool returns a WorkerPool with `limit` workers in the channel.
func NewWorkerPool(limit uint, name string) *WorkerPool {
	workers := make(chan *Worker, limit)
	for i := uint(0); i < limit; i++ {
		workers <- &Worker{ID: uint64(i + 1)}
	}
	return &WorkerPool{
		limit:   limit,
		workers: workers,
		name:    name,
	}
}

// Apply wait for an idle worker to run `taskFunc`.
// Notice: function `Apply` and `WaitFinished` cannot be called in parallel
func (pool *WorkerPool) Apply(fn taskFunc) {
	worker := pool.apply()
	pool.wg.Add(1)
	go func() {
		defer pool.wg.Done()
		defer pool.recycle(worker)
		fn()
	}()
}

// apply waits for an idle worker from the channel and return it
func (pool *WorkerPool) apply() *Worker {
	var worker *Worker
	select {
	case worker = <-pool.workers:
	default:
		//fmt.Printf("wait for workers, pool name is %s \n", pool.name)
		worker = <-pool.workers
	}
	return worker
}

// recycle sends an idle worker back to the channel
func (pool *WorkerPool) recycle(worker *Worker) {
	if worker == nil {
		panic("invalid restore worker")
	}
	pool.workers <- worker
}

// HasWorker checks if the pool has unallocated workers.
func (pool *WorkerPool) HasWorker() bool {
	return len(pool.workers) > 0
}

// WaitFinished waits till the pool finishs all the tasks.
func (pool *WorkerPool) WaitFinished() {
	pool.wg.Wait()
}
