package services

import (
	"sync"

	"github.com/fiskerinc/cloud-services/services/gateway/websocket"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/logger"
)

var connections *websocket.Connections
var connectionsOnce sync.Once

// GetConnections returns singleton instance of websocket Connections
func GetConnections() *websocket.Connections {
	connectionsOnce.Do(func() {
		connections = websocket.NewConnections(
		//		addSessionCallback,
		//		removeSessionCallback,
		)
	})
	return connections
}

func addSessionCallback(session websocket.SessionInterface) error {
	vin := session.GetID()
	uid := session.GetUUID()
	if session.IsDevice(common.HMI) {
		return AddHMISessionToManyCache(vin, uid)
	}

	return nil
}

func removeSessionCallback(session websocket.SessionInterface) error {
	vin := session.GetID()
	uid := session.GetUUID()

	if session.IsDevice(common.HMI) {
		return RemoveHMISessionFromManyCache(vin, uid)
	}

	return nil
}

func AddRemoveRedisListeners(add bool, id string) {
	if !add {
		if err := GetRedisPubSub().Remove(id); err != nil {
			logger.At(logger.Warn(), id, "Redis PubSub conn remove failed").Err(err).Send()
		}
		if err := GetRedisQueues().Remove(id); err != nil {
			logger.At(logger.Warn(), id, "Redis Queue conn remove failed").Err(err).Send()
		}
	} else {
		if err := GetRedisPubSub().Add(id); err != nil {
			logger.At(logger.Error(), id, "Redis PubSub conn add failed").Err(err).Send()
		}
		if err := GetRedisQueues().Add(id); err != nil {
			logger.At(logger.Error(), id, "Redis Queue conn add failed").Err(err).Send()
		}

	}
}
