package tokenize

import (
	"encoding/hex"
	"encoding/json"
	"git.nspix.com/golang/micro/helper/crypto"
	"git.nspix.com/golang/micro/helper/utils"
	"time"
)

var (
	defaultName = "@@micro@@"
)

type (
	entry struct {
		Uid       string    `json:"u"`
		ExpiredAt time.Time `json:"e"`
	}
)

//Encode encode token info
func Encode(name string, uid string, expiredAt time.Time) (token string, err error) {
	var (
		buf []byte
	)
	if buf, err = json.Marshal(entry{Uid: uid, ExpiredAt: expiredAt}); err != nil {
		return
	}
	if buf, err = crypto.AesEncrypt(buf, utils.MD5([]byte(defaultName+name))); err != nil {
		return
	}
	token = hex.EncodeToString(buf)
	return
}

//Decode decode token
func Decode(name string, token string) (uid string, expiredAt time.Time, err error) {
	var (
		buf []byte
		e   entry
	)
	if buf, err = hex.DecodeString(token); err != nil {
		return
	}
	if buf, err = crypto.AesDecrypt(buf, utils.MD5([]byte(defaultName+name))); err != nil {
		return
	}
	if err = json.Unmarshal(buf, &e); err == nil {
		uid = e.Uid
		expiredAt = e.ExpiredAt
	}
	return
}
