package pool

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/os/gmutex"
	"github.com/gogf/gf/v2/os/grpool"
	"github.com/gogf/gf/v2/util/gconv"
)

type Key string

const (
	AppleCardCallBack         Key = "apple_card_callback"
	AppleOrderProcessPushPool Key = "apple_order_process_push_pool"
	AppleCardTMallCallback    Key = "apple_card_t_mall_callback"
	AppleAccountCheckWallet   Key = "apple_account_check_wallet"
	JDCardCallBack            Key = "jd_card_callback"
	JDCardConsume             Key = "jd_card_consume"
	RedeemCardConsume         Key = "redeem_card_consume"
	RedeemCardCallback        Key = "redeem_card_callback"
	TMallAccountCallback      Key = "t_mall_game_account_callback"
	AccountDetect             Key = "account_detect"
)

func (k *Key) Key(key string) Key {
	return Key(fmt.Sprintf("%s-%s", gconv.String(k), key))
}

// Manager Pool 全局进程池
type Manager struct {
	Pools map[Key]*grpool.Pool
}

var (
	poolManager = &Manager{
		Pools: make(map[Key]*grpool.Pool),
	}
	mu gmutex.Mutex
)

func New(key Key, limit ...int) *grpool.Pool {
	pool := &grpool.Pool{}
	mu.LockFunc(func() {
		if readyPool, ok := poolManager.Pools[key]; ok && !readyPool.IsClosed() {
			pool = readyPool
		} else {
			newPool := grpool.New(limit...)
			poolManager.Pools[key] = newPool
			pool = newPool
		}
	})
	return pool
}

// GracefulDown 优雅关闭
func GracefulDown() {
	gmlock.LockFunc("pool_graceful_down", func() {
		for _, pool := range poolManager.Pools {
			pool.Close()
		}
	})
}
