package cache

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

func (p *RedisCache) HMGet(key string, fields ...string) ([]string, error) {
	args := []interface{}{"hmget", key}
	for _, val := range fields {
		args = append(args, val)
	}

	return p.commandReturnStringSlice(args...)
}

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

	return p.client.HGet(key, field).Result()
}

func (p *RedisCache) HGetAll(key string) (map[string]string, error) {
	if p.isCluster {
		return p.cluster.HGetAll(key).Result()
	}

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

func (p *RedisCache) HMSet(key string, fields map[string]interface{}) (string, error) {
	if p.isCluster {
		return p.cluster.HMSet(key, fields).Result()
	}

	return p.client.HMSet(key, fields).Result()
}

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

	return p.client.HSet(key, field, value).Result()
}

func (p *RedisCache) HIncrBy(key, field string, incr int64) (int64, error) {
	if p.isCluster {
		return p.cluster.HIncrBy(key, field, incr).Result()
	}

	return p.client.HIncrBy(key, field, incr).Result()
}

func (p *RedisCache) BatchHGetAll(keys ...string) (map[string]map[string]string, error) {
	cmds := make(map[string]*redis.StringStringMapCmd, len(keys))
	if p.isCluster {
		if _, err := p.cluster.Pipelined(func(pipe redis.Pipeliner) error {
			for _, key := range keys {
				cmds[key] = pipe.HGetAll(key)
			}
			return nil
		}); err != nil {
			return nil, err
		}
	} else {
		if _, err := p.client.Pipelined(func(pipe redis.Pipeliner) error {
			for _, key := range keys {
				cmds[key] = pipe.HGetAll(key)
			}
			return nil
		}); err != nil {
			return nil, err
		}
	}

	results := make(map[string]map[string]string, len(cmds))
	for _, key := range keys {
		if v, ok := cmds[key]; ok && v != nil {
			results[key] = v.Val()
		}
	}

	return results, nil
}
