package util

import (
	"bwallet/pkg/setting"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var jwtSecret []byte

type Claims struct {
	UserInfo UserInfo `json:"user"`
	jwt.StandardClaims
}

type UserInfo struct {
	Uid        int    `json:"uid"`
	Username   string `json:"username"`
	PlatformId int    `json:"platform_id"`
	Group      string `json:"group"`
}

func GenerateToken(username, password string) (string, error) {
	//nowTime := time.Now()
	//expireTime := nowTime.Add(3 * time.Hour)
	expiresTime := time.Now().Unix() + int64(60*60*24)

	claims := jwt.StandardClaims{
		Audience:  "https://www.bitfeel.cn",
		ExpiresAt: expiresTime,
		IssuedAt:  time.Now().Unix(),
		Issuer:    "https://www.bitfeel.cn",
		NotBefore: time.Now().Unix(),
		Subject:   "login",
	}
	var jwtSecret = []byte(setting.AppSetting.JwtSecret)

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
