package service

import (
	"sync"
	"time"

	"github.com/panjf2000/ants/v2"
)

type PriorityTask struct {
	Task func()
}

type PriorityQueue struct {
	tasks    []PriorityTask
	preTasks []PriorityTask
	pool     *ants.Pool
	mu       sync.Mutex
}

func NewPriorityQueue(poolSize int) *PriorityQueue {
	pool, _ := ants.NewPool(poolSize)
	pq := &PriorityQueue{
		tasks: make([]PriorityTask, poolSize),
		pool:  pool,
	}
	go pq.process()
	return pq
}

func (pq *PriorityQueue) process() {
	for {
		for _, task := range pq.tasks {
			err := pq.pool.Submit(task.Task)
			if err != nil {
				pq.mu.Lock()
				pq.preTasks = append(pq.preTasks, task)
				pq.mu.Unlock()
			}
		}
		pq.mu.Lock()
		pq.tasks = pq.preTasks
		pq.preTasks = make([]PriorityTask, 0)
		pq.mu.Unlock()
		if len(pq.tasks) == 0 {
			time.Sleep(time.Second * 5)
		}
	}
}

func (pq *PriorityQueue) Submit(task func()) {
	pq.mu.Lock()
	defer pq.mu.Unlock()
	pq.preTasks = append(pq.preTasks, PriorityTask{Task: task})
}

var (
	pool = NewPriorityQueue(50)
)
