package redisClient

import (
	"encoding/json"
	//~ "redis"
	"ssp/constants"
	"ssp/logger"

	//~ "fmt"
	"redis"
	"time"
)

var (
	client = &RedisClient{}
)

type RedisClient struct {
	c *redis.Client
}

// GetClient get the redis client
func Initialize() *RedisClient {
	c := redis.NewClient(&redis.Options{
		Addr:       constants.RedisHost + ":" + constants.RedisPort,
		Password:   constants.RedisPass,
		DB:         constants.RedisDbName,
		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{}, expiration time.Duration) error {
	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
}

// GetKey get key
func (client *RedisClient) GetKeyArray(key string, src interface{}) error {

	return nil
}

// SetKey set key
func (client *RedisClient) SetKeyArray(key string, value interface{}, expiration time.Duration) error {

	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) RPush(key string, value interface{}, end_limitation int64) {

	cacheEntry, _ := json.Marshal(value)

	client.c.LPush(key, cacheEntry)

	//~ val, _ := client.c.LRange(key,0,end_limitation).Result()

	//~ return len(val)

}

func (client *RedisClient) LRange(key string, end_limitation int64) []string {

	val, _ := client.c.LRange(key, 0, end_limitation).Result()

	return val

}

func (client *RedisClient) Del(key string) {

	client.c.Del(key)

}
