package token

import (
	"encoding/json"
	"time"
)

// Token is an OAuth2 token
type Token struct {
	AccessToken string
	Scope       Scope

	Issued    time.Time
	ExpiresIn time.Duration
}

type jsonMarshallableToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	Scope       string `json:"scope"`
}

// MarshalJSON implements json.Marshaler
func (t Token) MarshalJSON() ([]byte, error) {
	return json.Marshal(jsonMarshallableToken{
		AccessToken: t.AccessToken,
		ExpiresIn:   int(t.ExpiresIn.Seconds()),
		Scope:       t.Scope.String(),
	})
}

// UnmarshalJSON implements json.Unmarshaler
func (t *Token) UnmarshalJSON(in []byte) error {
	var raw jsonMarshallableToken
	if err := json.Unmarshal(in, &raw); err != nil {
		return err
	}

	t.AccessToken = raw.AccessToken
	t.ExpiresIn = time.Duration(raw.ExpiresIn) * time.Second
	t.Scope = ParseScope(raw.Scope)
	return nil
}
