package redisClient

import (
	"alpha/configuration"
	"alpha/logger"
	"encoding/json"
	"fmt"
	"redis"
	"time"
)

var (
	client = &RedisClient{}
)

type RedisClient struct {
	c *redis.Client
}

// GetClient get the redis client
func Initialize() *RedisClient {

	host := configuration.GetConfig("host", "redis")
	port := configuration.GetConfig("port", "redis")
	pass := configuration.GetConfig("password", "redis")

	c := redis.NewClient(&redis.Options{
		Addr:       host + ":" + port,
		Password:   pass,
		DB:         0,
		MaxConnAge: 1,
	})
	//defer c.Close()
	if err := c.Ping().Err(); err != nil {
		logger.Log.Println("Unable to connect to redis " + err.Error())
	}
	client.c = c
	return client
}

// GetKey get key
func (client *RedisClient) GetKey(key string, src interface{}) error {
	val, err := client.c.Get(key).Result()
	if err == redis.Nil || err != nil {
		return err
	}
	err = json.Unmarshal([]byte(val), &src)
	if err != nil {
		return err
	}
	return nil
}

// SetKey set key
func (client *RedisClient) SetKey(key string, value interface{}) error {

	expiration := time.Minute * 5

	cacheEntry, err := json.Marshal(value)
	if err != nil {
		return err
	}
	err = client.c.Set(key, cacheEntry, expiration).Err()
	if err != nil {
		return err
	}
	return nil
}

func (client *RedisClient) IfExists(key string) int64 {
	rp, err := client.c.Exists(key).Result()
	if err != nil {
		fmt.Println(err)
	}
	return rp
}
