package setting

import (
	"encoding/json"
	"sync"

	"github.com/QuantumNous/new-api/common"
)

var subscriptionGroups = map[string]string{}
var subscriptionGroupsMutex sync.RWMutex

func GetSubscriptionGroupsCopy() map[string]string {
	subscriptionGroupsMutex.RLock()
	defer subscriptionGroupsMutex.RUnlock()

	copy := make(map[string]string, len(subscriptionGroups))
	for k, v := range subscriptionGroups {
		copy[k] = v
	}
	return copy
}

func SubscriptionGroups2JSONString() string {
	subscriptionGroupsMutex.RLock()
	defer subscriptionGroupsMutex.RUnlock()

	jsonBytes, err := json.Marshal(subscriptionGroups)
	if err != nil {
		common.SysLog("error marshalling subscription groups: " + err.Error())
	}
	return string(jsonBytes)
}

func UpdateSubscriptionGroupsByJSONString(jsonStr string) error {
	subscriptionGroupsMutex.Lock()
	defer subscriptionGroupsMutex.Unlock()

	subscriptionGroups = make(map[string]string)
	return json.Unmarshal([]byte(jsonStr), &subscriptionGroups)
}

func IsSubscriptionGroup(name string) bool {
	subscriptionGroupsMutex.RLock()
	defer subscriptionGroupsMutex.RUnlock()

	_, ok := subscriptionGroups[name]
	return ok
}
