package redis

import (
	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	"code.justin.tv/chat/rediczar"
	"code.justin.tv/chat/rediczar/redefault"
	goredis "github.com/go-redis/redis/v7"
)

func newRedisClient(address string, isCluster bool, readonly bool, sampleReporter *telemetry.SampleReporter) *rediczar.Client {
	dependencyName := "redisPrimary"
	if readonly {
		dependencyName = "redisReadOnly"
	}
	middleware := newRedisMiddleware(*sampleReporter, dependencyName)

	if isCluster {
		return newRedisClusterClient(address, readonly, middleware)
	}
	return newStandaloneRedisClient(address, middleware)
}

func newRedisClusterClient(address string, readonly bool, middleware *redisMiddleware) *rediczar.Client {
	goRedisClient := redefault.NewClusterClient(address, &redefault.ClusterOpts{
		ReadOnly: readonly,
	})
	goRedisClient.AddHook(middleware)

	return &rediczar.Client{
		Commands: &rediczar.PrefixedCommands{
			Redis: goRedisClient,
		},
	}
}

func newStandaloneRedisClient(address string, middleware *redisMiddleware) *rediczar.Client {
	goRedisClient := goredis.NewClient(&goredis.Options{
		Addr: address,
	})
	goRedisClient.AddHook(middleware)

	return &rediczar.Client{
		Commands: &rediczar.PrefixedCommands{
			Redis: goRedisClient,
		},
	}
}
