// Copyright 2022 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package redis

import (
	"strconv"
	"time"

	"github.com/cloudwego/biz-demo/book-shop/pkg/conf"
	redigo "github.com/gomodule/redigo/redis"
)

var pool *redigo.Pool

func init() {
	pool = &redigo.Pool{
		Dial: func() (redigo.Conn, error) {
			c, err := redigo.Dial("tcp", conf.RedisAddress,
				redigo.DialConnectTimeout(500*time.Millisecond),
				redigo.DialReadTimeout(500*time.Millisecond),
				redigo.DialWriteTimeout(500*time.Millisecond))
			if err != nil {
				return nil, err
			}
			return c, nil
		},
		MaxIdle: conf.RedisConnPoolSize,
	}
}

func GetClient() redigo.Conn {
	return pool.Get()
}

func Upsert(userId int64, userInfo string) error {
	c := GetClient()
	defer c.Close()

	_, err := c.Do("SET", conf.RedisKey_User+strconv.FormatInt(userId, 10), userInfo)
	return err
}

func Del(userId int64) error {
	c := GetClient()
	defer c.Close()

	_, err := c.Do("DEL", conf.RedisKey_User+strconv.FormatInt(userId, 10))
	return err
}

func IsExist(userId int64) (bool, error) {
	c := GetClient()
	defer c.Close()

	isExist, err := redigo.Bool(c.Do("EXISTS", conf.RedisKey_User+strconv.FormatInt(userId, 10)))
	return isExist, err
}

func MGet(userIds []int64) ([]string, error) {
	c := GetClient()
	defer c.Close()

	keys := make([]interface{}, 0)
	for _, id := range userIds {
		keys = append(keys, conf.RedisKey_User+strconv.FormatInt(id, 10))
	}

	ret, err := redigo.Strings(c.Do("MGET", keys...))
	return ret, err
}
