package utils

import (
	"encoding/json"
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

var SessionTalentInfo = sessionTalentInfo{}
type sessionTalentInfo struct {

}

func (*sessionTalentInfo)GetTalentIdFromSession(r *ghttp.Request) (int, error) {
	t := r.GetHeader("Token")
	if t == "" {
		return -1, errors.New("not found info by token")
	}

	infoMap := r.Session.Get(t)
	if infoMap == nil {
		return 0, errors.New("info in session not found")
	}

	sInfoMap, ok := infoMap.(g.Map)
	if !ok {
		return 0, errors.New("info in session is not a map")
	}

	sTid := sInfoMap["talentId"]
	if sTid == nil {
		return 0, errors.New("session map not contains key talentId")
	}

	tid, err := sTid.(json.Number).Int64()
	if err != nil {
		return 0, errors.New("the type of talent id in session is not int")
	}

	return int(tid), nil
}
