package cache

import (
	"jannex/admin-dashboard-backend/modules/structs"
	"sort"
	"sync"
)

var categoryGroups []structs.CategoryGroup
var cgMu sync.RWMutex

func AddCategoryGroup(group structs.Group) {
	cgMu.Lock()
	defer cgMu.Unlock()

	for index, categoryGroup := range categoryGroups {
		if categoryGroup.Category == group.Category {
			categoryGroups[index].Groups = append(categoryGroups[index].Groups, group)
			return
		}
	}

	categoryGroup := structs.CategoryGroup{
		Category: group.Category,
	}

	categoryGroup.Groups = append(categoryGroup.Groups, group)
	categoryGroups = append(categoryGroups, categoryGroup)
}

func GetCategoryGroupByCategory(category string) structs.CategoryGroup {
	cgMu.RLock()
	defer cgMu.RUnlock()

	for _, categoryGroup := range categoryGroups {
		if categoryGroup.Category == category {
			return categoryGroup
		}
	}

	return structs.CategoryGroup{}
}

func RemoveAllCategoryGroupsByCategory(category string) {
	for index, categoryGroup := range GetCategoryGroups() {
		if categoryGroup.Category == category {
			cgMu.Lock()
			defer cgMu.Unlock()

			categoryGroups = append(categoryGroups[:index], categoryGroups[index+1:]...)
		}
	}
}

func GetCategoryGroupsSorted() []structs.CategoryGroup {
	cG := GetCategoryGroups()

	cgMu.Lock()
	defer cgMu.Unlock()

	sort.SliceStable(cG, func(i, j int) bool { return cG[i].Category < cG[j].Category })

	return cG
}

func GetCategoryGroups() []structs.CategoryGroup {
	cgMu.RLock()
	defer cgMu.RUnlock()

	return categoryGroups
}
