// +build !go1.7

package chitin

import (
	"fmt"
	"net/http"

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

func fetchContext(w http.ResponseWriter, r *http.Request) context.Context {
	if tr, ok := w.(*responseTracer); ok {
		return tr.ctx
	}

	// We're unable to access the context value because a middleware has
	// wrapped our specially-crafted http.ResponseWriter. Chitin will be near-
	// useless, since we won't be able to access the trace data or any chitin-
	// specific headers (which we removed when our middleware ran).
	//
	// This could possibly be worked around by keeping the context in a global
	// map keyed on something like the *http.Request or a header or the remote
	// network address, but those are considerably less desireable due to the
	// need for global state and (for the header and remote address) being
	// unreliable. Eww. And there's nothing stopping another middleware from
	// swapping out the *http.Request anyway (as we do ourselves).
	//
	// If we're at this code path, there's a bug with how the package is being
	// used. Let's not try to hide it, we've got to let the developer know so
	// they can fix it. Let's panic.
	err := fmt.Errorf("chitin:"+
		" unexpected http.ResponseWriter type %T prevents access"+
		" to the context value. See godoc for the chitin.Context"+
		" function for advice on its usage.", w)
	panic(err)
}

func requestWithContext(ctx context.Context, src *http.Request) (*http.Request, context.Context) {
	// The cancelation signal from the Request's Cancel field is part of the
	// Context value. We can ignore it here since it's handled in our caller.
	dst := new(http.Request)
	dst.Cancel = ctx.Done()
	return dst, ctx
}

func contextOfRequest(req *http.Request) context.Context {
	return context.Background()
}
