package devices

import (
	"errors"

	"golang.org/x/net/context"
)

const (
	storerKey = "code.secondbit.org/ducky/devices.hg#Storer"
)

var (
	// ErrNoStorerSet is returned when the Context has no Storer set in it.
	ErrNoStorerSet = errors.New("storerKey not set in Context")
	// ErrStorerKeyNotStorer is returned when there's a value in the Context for storerKey, but it's not a Storer.
	ErrStorerKeyNotStorer = errors.New("the value for storerKey does not fulfill the Storer interface")
)

// GetStorer returns the Storer associated with the passed Context.
// If no Storer is set, ErrNoStorerSet will be returned.
// If something that is not a Storer is set using the Storer's key,
// ErrStorerKeyNotStorer will be returned.
func GetStorer(c context.Context) (Storer, error) {
	val := c.Value(storerKey)
	if val == nil {
		return nil, ErrNoStorerSet
	}
	storer, ok := val.(Storer)
	if !ok {
		return nil, ErrStorerKeyNotStorer
	}
	return storer, nil
}

// WithStorer returns a Context that extends from the passed Context,
// but includes or overwrites the Storer key with the passed Storer.
func WithStorer(c context.Context, storer Storer) context.Context {
	return context.WithValue(c, storerKey, storer)
}
