package utils

import (
	"sync"

	"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
)

type ClusterClientManager struct {
	clients map[string]*versioned.Clientset
}

func NewClusterClientManager() *ClusterClientManager {
	return &ClusterClientManager{
		clients: make(map[string]*versioned.Clientset),
	}
}

func (c *ClusterClientManager) GetClient(regionCode string) *versioned.Clientset {
	return c.clients[regionCode]
}

func (c *ClusterClientManager) AddClient(regionCode string, client *versioned.Clientset) {
	c.clients[regionCode] = client
}

func (c *ClusterClientManager) RemoveClient(regionCode string) {
	delete(c.clients, regionCode)
}

func (c *ClusterClientManager) GetAllClients() map[string]*versioned.Clientset {
	return c.clients
}

func (c *ClusterClientManager) GetClientByRegionCode(regionCode string) *versioned.Clientset {
	return c.clients[regionCode]
}

func (c *ClusterClientManager) ForEach(fn func(regionCode string, client *versioned.Clientset)) {
	wg := sync.WaitGroup{}
	for regionCode, client := range c.clients {
		wg.Add(1)
		go func(regionCode string, client *versioned.Clientset) {
			defer wg.Done()
			fn(regionCode, client)
		}(regionCode, client)
	}
	wg.Wait()
}
