package sess

import (
	"encoding/json"
	"fmt"

	"git.clearsky.net.au/cody/gex.git/pkg/sess/jwt"
	"git.clearsky.net.au/cody/gex.git/pkg/srv"

	"time"
)

type Sess struct {
	req       *srv.Req
	res       srv.Res
	User_id   int
	User_name string
	Roles     []string
	Expires   time.Time
}

func (sess *Sess) HasRole(roleName string) bool {
	for _, role := range sess.Roles {
		if role == roleName {
			return true
		}
	}
	return false
}

func (sess *Sess) setDefaults() {
	sess.User_id = 0
	sess.User_name = "Guest"
	sess.Roles = []string{"Guest", "Everyone"}
	sess.Expires = Expires
}

func (sess *Sess) Construct(req *srv.Req, res srv.Res) {
	sess.req = req
	sess.res = res
	sess.setDefaults()

	// check cookie is valid (not expired too)
	cookie, err := req.Cookie(TokenName)

	if err != nil {
		//fmt.Println("cookie error")
		return
	}

	// decode jwt to json bytes
	jsonByt, err := jwt.Decode(cookie, Secret)
	if err != nil {
		fmt.Println("jwt decode error")
		return
	}

	// decode json bytes to session
	err = json.Unmarshal(jsonByt, &sess)
	if err != nil {
		fmt.Println("jwt to session error")
		return
	}

	// if session token has expired, return default session
	if time.Now().After(sess.Expires) {
		fmt.Println("session expired")
		sess.setDefaults()
	}

	sess.Expires = Expires

}

func (sess *Sess) Token() (string, error) {
	jsonStr, err := json.Marshal(sess)
	if err != nil {
		return "", err
	}

	// encode the json to jwt and set the cookie
	token, err := jwt.Encode(jsonStr, Secret)
	if err != nil {
		return "", err
	}
	return token, nil
}

// Saves token to cookie
func (sess *Sess) Save() {
	// get existing session or create new one

	// get the session token
	token, err := sess.Token()
	if err != nil {
		sess.res.Send(err.Error())
		return
	}

	// set the token cookie
	sess.res.Cookie(TokenName, token)
}
