package redis

import (
	"io"
	"log"
	"strconv"
	"time"
)

func formatFloat(f float64) string {
	return strconv.FormatFloat(f, 'f', -1, 64)
}

func formatInt(i int64) string {
	return strconv.FormatInt(i, 10)
}

func readTimeout(timeout time.Duration) time.Duration {
	if timeout == 0 {
		return 0
	}
	return timeout + time.Second
}

type commandable struct {
	process func(cmd Cmder)
}

func (c *commandable) Process(cmd Cmder) {
	c.process(cmd)
}

func usePrecise(dur time.Duration) bool {
	return dur < time.Second || dur%time.Second != 0
}

func formatMs(dur time.Duration) string {
	if dur > 0 && dur < time.Millisecond {
		log.Printf(
			"redis: specified duration is %s, but minimal supported value is %s",
			dur, time.Millisecond,
		)
	}
	return strconv.FormatInt(int64(dur/time.Millisecond), 10)
}

func formatSec(dur time.Duration) string {
	if dur > 0 && dur < time.Second {
		log.Printf(
			"redis: specified duration is %s, but minimal supported value is %s",
			dur, time.Second,
		)
	}
	return strconv.FormatInt(int64(dur/time.Second), 10)
}

//------------------------------------------------------------------------------

func (c *commandable) Auth(password string) *StatusCmd {
	cmd := newKeylessStatusCmd("AUTH", password)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Echo(message string) *StringCmd {
	cmd := NewStringCmd("ECHO", message)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) Ping() *StatusCmd {
	cmd := newKeylessStatusCmd("PING")
	c.Process(cmd)
	return cmd
}

func (c *commandable) Quit() *StatusCmd {
	panic("not implemented")
}

func (c *commandable) Select(index int64) *StatusCmd {
	cmd := newKeylessStatusCmd("SELECT", strconv.FormatInt(index, 10))
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) Del(keys ...string) *IntCmd {
	args := append([]string{"DEL"}, keys...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Dump(key string) *StringCmd {
	cmd := NewStringCmd("DUMP", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Exists(key string) *BoolCmd {
	cmd := NewBoolCmd("EXISTS", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Expire(key string, expiration time.Duration) *BoolCmd {
	cmd := NewBoolCmd("EXPIRE", key, formatSec(expiration))
	c.Process(cmd)
	return cmd
}

func (c *commandable) ExpireAt(key string, tm time.Time) *BoolCmd {
	cmd := NewBoolCmd("EXPIREAT", key, strconv.FormatInt(tm.Unix(), 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) Keys(pattern string) *StringSliceCmd {
	cmd := NewStringSliceCmd("KEYS", pattern)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Migrate(host, port, key string, db int64, timeout time.Duration) *StatusCmd {
	cmd := NewStatusCmd(
		"MIGRATE",
		host,
		port,
		key,
		strconv.FormatInt(db, 10),
		formatMs(timeout),
	)
	cmd._clusterKeyPos = 3
	cmd.setReadTimeout(readTimeout(timeout))
	c.Process(cmd)
	return cmd
}

func (c *commandable) Move(key string, db int64) *BoolCmd {
	cmd := NewBoolCmd("MOVE", key, strconv.FormatInt(db, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) ObjectRefCount(keys ...string) *IntCmd {
	args := append([]string{"OBJECT", "REFCOUNT"}, keys...)
	cmd := NewIntCmd(args...)
	cmd._clusterKeyPos = 2
	c.Process(cmd)
	return cmd
}

func (c *commandable) ObjectEncoding(keys ...string) *StringCmd {
	args := append([]string{"OBJECT", "ENCODING"}, keys...)
	cmd := NewStringCmd(args...)
	cmd._clusterKeyPos = 2
	c.Process(cmd)
	return cmd
}

func (c *commandable) ObjectIdleTime(keys ...string) *DurationCmd {
	args := append([]string{"OBJECT", "IDLETIME"}, keys...)
	cmd := NewDurationCmd(time.Second, args...)
	cmd._clusterKeyPos = 2
	c.Process(cmd)
	return cmd
}

func (c *commandable) Persist(key string) *BoolCmd {
	cmd := NewBoolCmd("PERSIST", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) PExpire(key string, expiration time.Duration) *BoolCmd {
	cmd := NewBoolCmd("PEXPIRE", key, formatMs(expiration))
	c.Process(cmd)
	return cmd
}

func (c *commandable) PExpireAt(key string, tm time.Time) *BoolCmd {
	cmd := NewBoolCmd(
		"PEXPIREAT",
		key,
		strconv.FormatInt(tm.UnixNano()/int64(time.Millisecond), 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) PTTL(key string) *DurationCmd {
	cmd := NewDurationCmd(time.Millisecond, "PTTL", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RandomKey() *StringCmd {
	cmd := NewStringCmd("RANDOMKEY")
	c.Process(cmd)
	return cmd
}

func (c *commandable) Rename(key, newkey string) *StatusCmd {
	cmd := NewStatusCmd("RENAME", key, newkey)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RenameNX(key, newkey string) *BoolCmd {
	cmd := NewBoolCmd("RENAMENX", key, newkey)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Restore(key string, ttl int64, value string) *StatusCmd {
	cmd := NewStatusCmd(
		"RESTORE",
		key,
		strconv.FormatInt(ttl, 10),
		value,
	)
	c.Process(cmd)
	return cmd
}

type Sort struct {
	By            string
	Offset, Count float64
	Get           []string
	Order         string
	IsAlpha       bool
	Store         string
}

func (c *commandable) Sort(key string, sort Sort) *StringSliceCmd {
	args := []string{"SORT", key}
	if sort.By != "" {
		args = append(args, "BY", sort.By)
	}
	if sort.Offset != 0 || sort.Count != 0 {
		args = append(args, "LIMIT", formatFloat(sort.Offset), formatFloat(sort.Count))
	}
	for _, get := range sort.Get {
		args = append(args, "GET", get)
	}
	if sort.Order != "" {
		args = append(args, sort.Order)
	}
	if sort.IsAlpha {
		args = append(args, "ALPHA")
	}
	if sort.Store != "" {
		args = append(args, "STORE", sort.Store)
	}
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) TTL(key string) *DurationCmd {
	cmd := NewDurationCmd(time.Second, "TTL", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Type(key string) *StatusCmd {
	cmd := NewStatusCmd("TYPE", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Scan(cursor int64, match string, count int64) *ScanCmd {
	args := []string{"SCAN", strconv.FormatInt(cursor, 10)}
	if match != "" {
		args = append(args, "MATCH", match)
	}
	if count > 0 {
		args = append(args, "COUNT", strconv.FormatInt(count, 10))
	}
	cmd := NewScanCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SScan(key string, cursor int64, match string, count int64) *ScanCmd {
	args := []string{"SSCAN", key, strconv.FormatInt(cursor, 10)}
	if match != "" {
		args = append(args, "MATCH", match)
	}
	if count > 0 {
		args = append(args, "COUNT", strconv.FormatInt(count, 10))
	}
	cmd := NewScanCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HScan(key string, cursor int64, match string, count int64) *ScanCmd {
	args := []string{"HSCAN", key, strconv.FormatInt(cursor, 10)}
	if match != "" {
		args = append(args, "MATCH", match)
	}
	if count > 0 {
		args = append(args, "COUNT", strconv.FormatInt(count, 10))
	}
	cmd := NewScanCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZScan(key string, cursor int64, match string, count int64) *ScanCmd {
	args := []string{"ZSCAN", key, strconv.FormatInt(cursor, 10)}
	if match != "" {
		args = append(args, "MATCH", match)
	}
	if count > 0 {
		args = append(args, "COUNT", strconv.FormatInt(count, 10))
	}
	cmd := NewScanCmd(args...)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) Append(key, value string) *IntCmd {
	cmd := NewIntCmd("APPEND", key, value)
	c.Process(cmd)
	return cmd
}

type BitCount struct {
	Start, End int64
}

func (c *commandable) BitCount(key string, bitCount *BitCount) *IntCmd {
	args := []string{"BITCOUNT", key}
	if bitCount != nil {
		args = append(
			args,
			strconv.FormatInt(bitCount.Start, 10),
			strconv.FormatInt(bitCount.End, 10),
		)
	}
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) bitOp(op, destKey string, keys ...string) *IntCmd {
	args := []string{"BITOP", op, destKey}
	args = append(args, keys...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) BitOpAnd(destKey string, keys ...string) *IntCmd {
	return c.bitOp("AND", destKey, keys...)
}

func (c *commandable) BitOpOr(destKey string, keys ...string) *IntCmd {
	return c.bitOp("OR", destKey, keys...)
}

func (c *commandable) BitOpXor(destKey string, keys ...string) *IntCmd {
	return c.bitOp("XOR", destKey, keys...)
}

func (c *commandable) BitOpNot(destKey string, key string) *IntCmd {
	return c.bitOp("NOT", destKey, key)
}

func (c *commandable) BitPos(key string, bit int64, pos ...int64) *IntCmd {
	args := []string{"BITPOS", key, formatInt(bit)}
	switch len(pos) {
	case 0:
	case 1:
		args = append(args, formatInt(pos[0]))
	case 2:
		args = append(args, formatInt(pos[0]), formatInt(pos[1]))
	default:
		panic("too many arguments")
	}
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Decr(key string) *IntCmd {
	cmd := NewIntCmd("DECR", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) DecrBy(key string, decrement int64) *IntCmd {
	cmd := NewIntCmd("DECRBY", key, strconv.FormatInt(decrement, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) Get(key string) *StringCmd {
	cmd := NewStringCmd("GET", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) GetBit(key string, offset int64) *IntCmd {
	cmd := NewIntCmd("GETBIT", key, strconv.FormatInt(offset, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) GetRange(key string, start, end int64) *StringCmd {
	cmd := NewStringCmd(
		"GETRANGE",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(end, 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) GetSet(key, value string) *StringCmd {
	cmd := NewStringCmd("GETSET", key, value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Incr(key string) *IntCmd {
	cmd := NewIntCmd("INCR", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) IncrBy(key string, value int64) *IntCmd {
	cmd := NewIntCmd("INCRBY", key, strconv.FormatInt(value, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) IncrByFloat(key string, value float64) *FloatCmd {
	cmd := NewFloatCmd("INCRBYFLOAT", key, formatFloat(value))
	c.Process(cmd)
	return cmd
}

func (c *commandable) MGet(keys ...string) *SliceCmd {
	args := append([]string{"MGET"}, keys...)
	cmd := NewSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) MSet(pairs ...string) *StatusCmd {
	args := append([]string{"MSET"}, pairs...)
	cmd := NewStatusCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) MSetNX(pairs ...string) *BoolCmd {
	args := append([]string{"MSETNX"}, pairs...)
	cmd := NewBoolCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) PSetEx(key string, expiration time.Duration, value string) *StatusCmd {
	cmd := NewStatusCmd("PSETEX", key, formatMs(expiration), value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) Set(key, value string, expiration time.Duration) *StatusCmd {
	args := []string{"SET", key, value}
	if expiration > 0 {
		if usePrecise(expiration) {
			args = append(args, "PX", formatMs(expiration))
		} else {
			args = append(args, "EX", formatSec(expiration))
		}
	}
	cmd := NewStatusCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SetBit(key string, offset int64, value int) *IntCmd {
	cmd := NewIntCmd(
		"SETBIT",
		key,
		strconv.FormatInt(offset, 10),
		strconv.FormatInt(int64(value), 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SetEx(key string, expiration time.Duration, value string) *StatusCmd {
	cmd := NewStatusCmd("SETEX", key, formatSec(expiration), value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SetNX(key, value string, expiration time.Duration) *BoolCmd {
	var cmd *BoolCmd
	if expiration == 0 {
		// Use old `SETNX` to support old Redis versions.
		cmd = NewBoolCmd("SETNX", key, value)
	} else {
		if usePrecise(expiration) {
			cmd = NewBoolCmd("SET", key, value, "PX", formatMs(expiration), "NX")
		} else {
			cmd = NewBoolCmd("SET", key, value, "EX", formatSec(expiration), "NX")
		}
	}
	c.Process(cmd)
	return cmd
}

func (c *Client) SetXX(key, value string, expiration time.Duration) *BoolCmd {
	var cmd *BoolCmd
	if usePrecise(expiration) {
		cmd = NewBoolCmd("SET", key, value, "PX", formatMs(expiration), "XX")
	} else {
		cmd = NewBoolCmd("SET", key, value, "EX", formatSec(expiration), "XX")
	}
	c.Process(cmd)
	return cmd
}

func (c *commandable) SetRange(key string, offset int64, value string) *IntCmd {
	cmd := NewIntCmd("SETRANGE", key, strconv.FormatInt(offset, 10), value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) StrLen(key string) *IntCmd {
	cmd := NewIntCmd("STRLEN", key)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) HDel(key string, fields ...string) *IntCmd {
	args := append([]string{"HDEL", key}, fields...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HExists(key, field string) *BoolCmd {
	cmd := NewBoolCmd("HEXISTS", key, field)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HGet(key, field string) *StringCmd {
	cmd := NewStringCmd("HGET", key, field)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HGetAll(key string) *StringSliceCmd {
	cmd := NewStringSliceCmd("HGETALL", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HGetAllMap(key string) *StringStringMapCmd {
	cmd := NewStringStringMapCmd("HGETALL", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HIncrBy(key, field string, incr int64) *IntCmd {
	cmd := NewIntCmd("HINCRBY", key, field, strconv.FormatInt(incr, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) HIncrByFloat(key, field string, incr float64) *FloatCmd {
	cmd := NewFloatCmd("HINCRBYFLOAT", key, field, formatFloat(incr))
	c.Process(cmd)
	return cmd
}

func (c *commandable) HKeys(key string) *StringSliceCmd {
	cmd := NewStringSliceCmd("HKEYS", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HLen(key string) *IntCmd {
	cmd := NewIntCmd("HLEN", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HMGet(key string, fields ...string) *SliceCmd {
	args := append([]string{"HMGET", key}, fields...)
	cmd := NewSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HMSet(key, field, value string, pairs ...string) *StatusCmd {
	args := append([]string{"HMSET", key, field, value}, pairs...)
	cmd := NewStatusCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HSet(key, field, value string) *BoolCmd {
	cmd := NewBoolCmd("HSET", key, field, value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HSetNX(key, field, value string) *BoolCmd {
	cmd := NewBoolCmd("HSETNX", key, field, value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) HVals(key string) *StringSliceCmd {
	cmd := NewStringSliceCmd("HVALS", key)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) BLPop(timeout time.Duration, keys ...string) *StringSliceCmd {
	args := append([]string{"BLPOP"}, keys...)
	args = append(args, formatSec(timeout))
	cmd := NewStringSliceCmd(args...)
	cmd.setReadTimeout(readTimeout(timeout))
	c.Process(cmd)
	return cmd
}

func (c *commandable) BRPop(timeout time.Duration, keys ...string) *StringSliceCmd {
	args := append([]string{"BRPOP"}, keys...)
	args = append(args, formatSec(timeout))
	cmd := NewStringSliceCmd(args...)
	cmd.setReadTimeout(readTimeout(timeout))
	c.Process(cmd)
	return cmd
}

func (c *commandable) BRPopLPush(source, destination string, timeout time.Duration) *StringCmd {
	cmd := NewStringCmd(
		"BRPOPLPUSH",
		source,
		destination,
		formatSec(timeout),
	)
	cmd.setReadTimeout(readTimeout(timeout))
	c.Process(cmd)
	return cmd
}

func (c *commandable) LIndex(key string, index int64) *StringCmd {
	cmd := NewStringCmd("LINDEX", key, strconv.FormatInt(index, 10))
	c.Process(cmd)
	return cmd
}

func (c *commandable) LInsert(key, op, pivot, value string) *IntCmd {
	cmd := NewIntCmd("LINSERT", key, op, pivot, value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LLen(key string) *IntCmd {
	cmd := NewIntCmd("LLEN", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LPop(key string) *StringCmd {
	cmd := NewStringCmd("LPOP", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LPush(key string, values ...string) *IntCmd {
	args := append([]string{"LPUSH", key}, values...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LPushX(key, value string) *IntCmd {
	cmd := NewIntCmd("LPUSHX", key, value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LRange(key string, start, stop int64) *StringSliceCmd {
	cmd := NewStringSliceCmd(
		"LRANGE",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(stop, 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LRem(key string, count int64, value string) *IntCmd {
	cmd := NewIntCmd("LREM", key, strconv.FormatInt(count, 10), value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LSet(key string, index int64, value string) *StatusCmd {
	cmd := NewStatusCmd("LSET", key, strconv.FormatInt(index, 10), value)
	c.Process(cmd)
	return cmd
}

func (c *commandable) LTrim(key string, start, stop int64) *StatusCmd {
	cmd := NewStatusCmd(
		"LTRIM",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(stop, 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RPop(key string) *StringCmd {
	cmd := NewStringCmd("RPOP", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RPopLPush(source, destination string) *StringCmd {
	cmd := NewStringCmd("RPOPLPUSH", source, destination)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RPush(key string, values ...string) *IntCmd {
	args := append([]string{"RPUSH", key}, values...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) RPushX(key string, value string) *IntCmd {
	cmd := NewIntCmd("RPUSHX", key, value)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) SAdd(key string, members ...string) *IntCmd {
	args := append([]string{"SADD", key}, members...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SCard(key string) *IntCmd {
	cmd := NewIntCmd("SCARD", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SDiff(keys ...string) *StringSliceCmd {
	args := append([]string{"SDIFF"}, keys...)
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SDiffStore(destination string, keys ...string) *IntCmd {
	args := append([]string{"SDIFFSTORE", destination}, keys...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SInter(keys ...string) *StringSliceCmd {
	args := append([]string{"SINTER"}, keys...)
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SInterStore(destination string, keys ...string) *IntCmd {
	args := append([]string{"SINTERSTORE", destination}, keys...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SIsMember(key, member string) *BoolCmd {
	cmd := NewBoolCmd("SISMEMBER", key, member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SMembers(key string) *StringSliceCmd {
	cmd := NewStringSliceCmd("SMEMBERS", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SMove(source, destination, member string) *BoolCmd {
	cmd := NewBoolCmd("SMOVE", source, destination, member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SPop(key string) *StringCmd {
	cmd := NewStringCmd("SPOP", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SRandMember(key string) *StringCmd {
	cmd := NewStringCmd("SRANDMEMBER", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SRem(key string, members ...string) *IntCmd {
	args := append([]string{"SREM", key}, members...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SUnion(keys ...string) *StringSliceCmd {
	args := append([]string{"SUNION"}, keys...)
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SUnionStore(destination string, keys ...string) *IntCmd {
	args := append([]string{"SUNIONSTORE", destination}, keys...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

type Z struct {
	Score  float64
	Member string
}

type ZStore struct {
	Weights   []int64
	Aggregate string
}

func (c *commandable) ZAdd(key string, members ...Z) *IntCmd {
	args := []string{"ZADD", key}
	for _, m := range members {
		args = append(args, formatFloat(m.Score), m.Member)
	}
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZCard(key string) *IntCmd {
	cmd := NewIntCmd("ZCARD", key)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZCount(key, min, max string) *IntCmd {
	cmd := NewIntCmd("ZCOUNT", key, min, max)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZIncrBy(key string, increment float64, member string) *FloatCmd {
	cmd := NewFloatCmd("ZINCRBY", key, formatFloat(increment), member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZInterStore(
	destination string,
	store ZStore,
	keys ...string,
) *IntCmd {
	args := []string{"ZINTERSTORE", destination, strconv.FormatInt(int64(len(keys)), 10)}
	args = append(args, keys...)
	if len(store.Weights) > 0 {
		args = append(args, "WEIGHTS")
		for _, weight := range store.Weights {
			args = append(args, strconv.FormatInt(weight, 10))
		}
	}
	if store.Aggregate != "" {
		args = append(args, "AGGREGATE", store.Aggregate)
	}
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) zRange(key string, start, stop int64, withScores bool) *StringSliceCmd {
	args := []string{
		"ZRANGE",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(stop, 10),
	}
	if withScores {
		args = append(args, "WITHSCORES")
	}
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRange(key string, start, stop int64) *StringSliceCmd {
	return c.zRange(key, start, stop, false)
}

func (c *commandable) ZRangeWithScores(key string, start, stop int64) *ZSliceCmd {
	args := []string{
		"ZRANGE",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(stop, 10),
		"WITHSCORES",
	}
	cmd := NewZSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

type ZRangeByScore struct {
	Min, Max      string
	Offset, Count int64
}

func (c *commandable) zRangeByScore(key string, opt ZRangeByScore, withScores bool) *StringSliceCmd {
	args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max}
	if withScores {
		args = append(args, "WITHSCORES")
	}
	if opt.Offset != 0 || opt.Count != 0 {
		args = append(
			args,
			"LIMIT",
			strconv.FormatInt(opt.Offset, 10),
			strconv.FormatInt(opt.Count, 10),
		)
	}
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd {
	return c.zRangeByScore(key, opt, false)
}

func (c *commandable) ZRangeByScoreWithScores(key string, opt ZRangeByScore) *ZSliceCmd {
	args := []string{"ZRANGEBYSCORE", key, opt.Min, opt.Max, "WITHSCORES"}
	if opt.Offset != 0 || opt.Count != 0 {
		args = append(
			args,
			"LIMIT",
			strconv.FormatInt(opt.Offset, 10),
			strconv.FormatInt(opt.Count, 10),
		)
	}
	cmd := NewZSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRank(key, member string) *IntCmd {
	cmd := NewIntCmd("ZRANK", key, member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRem(key string, members ...string) *IntCmd {
	args := append([]string{"ZREM", key}, members...)
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRemRangeByRank(key string, start, stop int64) *IntCmd {
	cmd := NewIntCmd(
		"ZREMRANGEBYRANK",
		key,
		strconv.FormatInt(start, 10),
		strconv.FormatInt(stop, 10),
	)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRemRangeByScore(key, min, max string) *IntCmd {
	cmd := NewIntCmd("ZREMRANGEBYSCORE", key, min, max)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRevRange(key string, start, stop int64) *StringSliceCmd {
	cmd := NewStringSliceCmd("ZREVRANGE", key, formatInt(start), formatInt(stop))
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRevRangeWithScores(key string, start, stop int64) *ZSliceCmd {
	cmd := NewZSliceCmd("ZREVRANGE", key, formatInt(start), formatInt(stop), "WITHSCORES")
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRevRangeByScore(key string, opt ZRangeByScore) *StringSliceCmd {
	args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min}
	if opt.Offset != 0 || opt.Count != 0 {
		args = append(
			args,
			"LIMIT",
			strconv.FormatInt(opt.Offset, 10),
			strconv.FormatInt(opt.Count, 10),
		)
	}
	cmd := NewStringSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRevRangeByScoreWithScores(key string, opt ZRangeByScore) *ZSliceCmd {
	args := []string{"ZREVRANGEBYSCORE", key, opt.Max, opt.Min, "WITHSCORES"}
	if opt.Offset != 0 || opt.Count != 0 {
		args = append(
			args,
			"LIMIT",
			strconv.FormatInt(opt.Offset, 10),
			strconv.FormatInt(opt.Count, 10),
		)
	}
	cmd := NewZSliceCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZRevRank(key, member string) *IntCmd {
	cmd := NewIntCmd("ZREVRANK", key, member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZScore(key, member string) *FloatCmd {
	cmd := NewFloatCmd("ZSCORE", key, member)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ZUnionStore(dest string, store ZStore, keys ...string) *IntCmd {
	args := []string{"ZUNIONSTORE", dest, strconv.FormatInt(int64(len(keys)), 10)}
	args = append(args, keys...)
	if len(store.Weights) > 0 {
		args = append(args, "WEIGHTS")
		for _, weight := range store.Weights {
			args = append(args, strconv.FormatInt(weight, 10))
		}
	}
	if store.Aggregate != "" {
		args = append(args, "AGGREGATE", store.Aggregate)
	}
	cmd := NewIntCmd(args...)
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) BgRewriteAOF() *StatusCmd {
	cmd := NewStatusCmd("BGREWRITEAOF")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) BgSave() *StatusCmd {
	cmd := NewStatusCmd("BGSAVE")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClientKill(ipPort string) *StatusCmd {
	cmd := NewStatusCmd("CLIENT", "KILL", ipPort)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClientList() *StringCmd {
	cmd := NewStringCmd("CLIENT", "LIST")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ConfigGet(parameter string) *SliceCmd {
	cmd := NewSliceCmd("CONFIG", "GET", parameter)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ConfigResetStat() *StatusCmd {
	cmd := NewStatusCmd("CONFIG", "RESETSTAT")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ConfigSet(parameter, value string) *StatusCmd {
	cmd := NewStatusCmd("CONFIG", "SET", parameter, value)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) DbSize() *IntCmd {
	cmd := NewIntCmd("DBSIZE")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) FlushAll() *StatusCmd {
	cmd := newKeylessStatusCmd("FLUSHALL")
	c.Process(cmd)
	return cmd
}

func (c *commandable) FlushDb() *StatusCmd {
	cmd := newKeylessStatusCmd("FLUSHDB")
	c.Process(cmd)
	return cmd
}

func (c *commandable) Info() *StringCmd {
	cmd := NewStringCmd("INFO")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) LastSave() *IntCmd {
	cmd := NewIntCmd("LASTSAVE")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) Save() *StatusCmd {
	cmd := newKeylessStatusCmd("SAVE")
	c.Process(cmd)
	return cmd
}

func (c *commandable) shutdown(modifier string) *StatusCmd {
	var args []string
	if modifier == "" {
		args = []string{"SHUTDOWN"}
	} else {
		args = []string{"SHUTDOWN", modifier}
	}
	cmd := newKeylessStatusCmd(args...)
	c.Process(cmd)
	if err := cmd.Err(); err != nil {
		if err == io.EOF {
			// Server quit as expected.
			cmd.err = nil
		}
	} else {
		// Server did not quit. String reply contains the reason.
		cmd.err = errorf(cmd.val)
		cmd.val = ""
	}
	return cmd
}

func (c *commandable) Shutdown() *StatusCmd {
	return c.shutdown("")
}

func (c *commandable) ShutdownSave() *StatusCmd {
	return c.shutdown("SAVE")
}

func (c *commandable) ShutdownNoSave() *StatusCmd {
	return c.shutdown("NOSAVE")
}

func (c *commandable) SlaveOf(host, port string) *StatusCmd {
	cmd := newKeylessStatusCmd("SLAVEOF", host, port)
	c.Process(cmd)
	return cmd
}

func (c *commandable) SlowLog() {
	panic("not implemented")
}

func (c *commandable) Sync() {
	panic("not implemented")
}

func (c *commandable) Time() *StringSliceCmd {
	cmd := NewStringSliceCmd("TIME")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) Eval(script string, keys []string, args []string) *Cmd {
	cmdArgs := []string{"EVAL", script, strconv.FormatInt(int64(len(keys)), 10)}
	cmdArgs = append(cmdArgs, keys...)
	cmdArgs = append(cmdArgs, args...)
	cmd := NewCmd(cmdArgs...)
	if len(keys) > 0 {
		cmd._clusterKeyPos = 3
	}
	c.Process(cmd)
	return cmd
}

func (c *commandable) EvalSha(sha1 string, keys []string, args []string) *Cmd {
	cmdArgs := []string{"EVALSHA", sha1, strconv.FormatInt(int64(len(keys)), 10)}
	cmdArgs = append(cmdArgs, keys...)
	cmdArgs = append(cmdArgs, args...)
	cmd := NewCmd(cmdArgs...)
	if len(keys) > 0 {
		cmd._clusterKeyPos = 3
	}
	c.Process(cmd)
	return cmd
}

func (c *commandable) ScriptExists(scripts ...string) *BoolSliceCmd {
	args := append([]string{"SCRIPT", "EXISTS"}, scripts...)
	cmd := NewBoolSliceCmd(args...)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ScriptFlush() *StatusCmd {
	cmd := newKeylessStatusCmd("SCRIPT", "FLUSH")
	c.Process(cmd)
	return cmd
}

func (c *commandable) ScriptKill() *StatusCmd {
	cmd := newKeylessStatusCmd("SCRIPT", "KILL")
	c.Process(cmd)
	return cmd
}

func (c *commandable) ScriptLoad(script string) *StringCmd {
	cmd := NewStringCmd("SCRIPT", "LOAD", script)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) DebugObject(key string) *StringCmd {
	cmd := NewStringCmd("DEBUG", "OBJECT", key)
	cmd._clusterKeyPos = 2
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) PubSubChannels(pattern string) *StringSliceCmd {
	args := []string{"PUBSUB", "CHANNELS"}
	if pattern != "*" {
		args = append(args, pattern)
	}
	cmd := NewStringSliceCmd(args...)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) PubSubNumSub(channels ...string) *StringIntMapCmd {
	args := []string{"PUBSUB", "NUMSUB"}
	args = append(args, channels...)
	cmd := NewStringIntMapCmd(args...)
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) PubSubNumPat() *IntCmd {
	cmd := NewIntCmd("PUBSUB", "NUMPAT")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

//------------------------------------------------------------------------------

func (c *commandable) ClusterSlots() *ClusterSlotCmd {
	cmd := NewClusterSlotCmd("CLUSTER", "slots")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterNodes() *StringCmd {
	cmd := NewStringCmd("CLUSTER", "nodes")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterMeet(host, port string) *StatusCmd {
	cmd := newKeylessStatusCmd("CLUSTER", "meet", host, port)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterReplicate(nodeID string) *StatusCmd {
	cmd := newKeylessStatusCmd("CLUSTER", "replicate", nodeID)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterInfo() *StringCmd {
	cmd := NewStringCmd("CLUSTER", "info")
	cmd._clusterKeyPos = 0
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterFailover() *StatusCmd {
	cmd := newKeylessStatusCmd("CLUSTER", "failover")
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterAddSlots(slots ...int) *StatusCmd {
	args := make([]string, len(slots)+2)
	args[0] = "CLUSTER"
	args[1] = "addslots"
	for i, num := range slots {
		args[i+2] = strconv.Itoa(num)
	}
	cmd := newKeylessStatusCmd(args...)
	c.Process(cmd)
	return cmd
}

func (c *commandable) ClusterAddSlotsRange(min, max int) *StatusCmd {
	size := max - min + 1
	slots := make([]int, size)
	for i := 0; i < size; i++ {
		slots[i] = min + i
	}
	return c.ClusterAddSlots(slots...)
}