package wechat

import (
	"context"
	"fmt"
	"github.com/go-redis/redis"
	"time"
)

const AccessTokenKey = "wechat:access_token:%s"

type AccessToken struct {
	Client redis.UniversalClient
	ctx    context.Context
}

func NewAccessToken(client redis.UniversalClient) *AccessToken {
	return &AccessToken{Client: client, ctx: context.Background()}
}

func (this *AccessToken) Get(key string) interface{} {
	val := this.Client.Get(fmt.Sprintf(AccessTokenKey, key)).Val()
	if val == "" {
		return nil
	}
	return val
}

func (this *AccessToken) Set(key string, val interface{}, timeout time.Duration) error {
	return this.Client.Set(fmt.Sprintf(AccessTokenKey, key), val, timeout).Err()
}

func (this *AccessToken) IsExist(key string) bool {
	return this.Client.Exists(fmt.Sprintf(AccessTokenKey, key)).Val() == 1
}

func (this *AccessToken) Delete(key string) error {
	return this.Client.Del(fmt.Sprintf(AccessTokenKey, key)).Err()
}
