package cache

import (
	"time"

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

func (p *RedisCache) Get(key string) (string, error) {
	if p.isCluster {
		return p.cluster.Get(key).Result()
	}

	return p.client.Get(key).Result()
}

func (p *RedisCache) Set(key string, value interface{}) (string, error) {
	if p.isCluster {
		return p.cluster.Set(key, value, 0).Result()
	}

	return p.client.Set(key, value, 0).Result()
}

func (p *RedisCache) SetEx(key string, seconds int64, value interface{}) (string, error) {
	if p.isCluster {
		return p.cluster.Set(key, value, time.Duration(seconds)*time.Second).Result()
	}

	return p.client.Set(key, value, time.Duration(seconds)*time.Second).Result()
}

func (p *RedisCache) MGet(keys ...string) ([]string, error) {
	if p.isCluster {
		results := make([]string, 0, len(keys))
		for _, key := range keys {
			v, err := p.cluster.Get(key).Result()
			if err != nil {
				if err != redis.Nil {
					return nil, err
				}
			}

			results = append(results, v)
		}

		if len(results) <= 0 {
			return nil, redis.Nil
		}

		return results, nil
	}

	args := []interface{}{"mget"}
	for _, key := range keys {
		args = append(args, key)
	}
	return p.commandReturnStringSlice(args...)
}

func (p *RedisCache) SetBit(key string, offset int64, value int) (int64, error) {
	if p.isCluster {
		return p.cluster.SetBit(key, offset, value).Result()
	}

	return p.client.SetBit(key, offset, value).Result()
}

func (p *RedisCache) GetBit(key string, offset int64) (int64, error) {
	if p.isCluster {
		return p.cluster.GetBit(key, offset).Result()
	}

	return p.client.GetBit(key, offset).Result()
}

func (p *RedisCache) SetNx(key string, value interface{}) (bool, error) {
	if p.isCluster {
		return p.cluster.SetNX(key, value, 0).Result()
	}

	return p.client.SetNX(key, value, 0).Result()
}

func (p *RedisCache) SetNxEx(key string, value interface{}, seconds int64) (bool, error) {
	if p.isCluster {
		return p.cluster.SetNX(key, value, time.Duration(seconds)*time.Second).Result()
	}

	return p.client.SetNX(key, value, time.Duration(seconds)*time.Second).Result()
}

func (p *RedisCache) Append(key, value string) (int64, error) {
	if p.isCluster {
		return p.cluster.Append(key, value).Result()
	}

	return p.client.Append(key, value).Result()
}
