package socketclients

import (
	"strings"

	"lms.de/backend/modules/cache"
	"lms.de/backend/modules/structs"
)

func BroadcastMessage(organizationId string, sendSocketMessage structs.SendSocketMessage) {
	for _, client := range cache.GetSocketClients() {
		if client.OrganizationId == organizationId {
			client.SendMessage(sendSocketMessage)
		}
	}
}

func BroadcastMessageToTopic(organizationId string, topic string, sendSocketMessage structs.SendSocketMessage) {
	for _, client := range cache.GetSocketClients() {
		if hasClientSubscribedToTopic(topic, client.SubscribedTopic) {
			client.SendMessage(sendSocketMessage)
		}
	}
}

func BroadcastMessageExceptBrowserTabSession(organizationId string, browserTabSession string, sendSocketMessage structs.SendSocketMessage) {
	for _, client := range cache.GetSocketClients() {
		if client.OrganizationId == organizationId && client.BrowserTabSession != browserTabSession {
			client.SendMessage(sendSocketMessage)
		}
	}
}

func BroadcastMessageToTopicExceptBrowserTabSession(organizationId string, topic string, browserTabSession string, sendSocketMessage structs.SendSocketMessage) {
	for _, client := range cache.GetSocketClients() {
		if hasClientSubscribedToTopic(topic, client.SubscribedTopic) && client.BrowserTabSession != browserTabSession && client.OrganizationId == organizationId {
			client.SendMessage(sendSocketMessage)
		}
	}
}

func hasClientSubscribedToTopic(topic string, clientTopic string) bool {
	return clientTopic == topic || strings.HasPrefix(clientTopic, topic)
}
