package memstore

import (
	"errors"
	"time"

	"github.com/go-redis/redis"
)

var redisStore *redis.Client

// InitClient -
func InitClient() error {
	redisStore = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	_, err := redisStore.Ping().Result()
	return err
}

// RedisSet -
func RedisSet(namespace, key string, val string, expire int) error {
	var t time.Duration
	if expire > 0 {
		t = time.Second * time.Duration(expire)
	}
	var n string
	if len(namespace) > 0 {
		n += namespace
		n += ":"
	}

	if len(key) == 0 {
		return errors.New("key empty")
	}

	n += key

	err := redisStore.Set(n, val, t).Err()
	return err
}

// RedisGet -
func RedisGet(namespace, key string) (string, error) {
	var n string
	if len(namespace) > 0 {
		n += namespace
		n += ":"
	}

	if len(key) == 0 {
		return "", errors.New("key empty")
	}

	n += key

	val, err := redisStore.Get(n).Result()
	return val, err
}

// RedisDel -
func RedisDel(namespace, key string) error {
	var n string
	if len(namespace) > 0 {
		n += namespace
		n += ":"
	}

	if len(key) == 0 {
		return errors.New("key empty")
	}

	n += key

	err := redisStore.Del(n).Err()
	return err
}
