package middleware

import (
	"context"
	"net/http"
	"path/filepath"
	"time"

	"github.com/Xe/ln"
	"golang.org/x/net/trace"
)

// Trace adds go stdlib tracing to this http handler.
func Trace(family string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			sp := trace.New(filepath.Base(family), r.Host+r.RequestURI)
			defer sp.Finish()
			ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
			defer cancel()

			ctx = trace.NewContext(ctx, sp)
			f := ln.F{
				"family":      family,
				"method":      r.Method,
				"path":        r.URL.Path,
				"remote_addr": r.RemoteAddr,
				"user_agent":  r.UserAgent(),
			}
			ctx = ln.WithF(ctx, f)

			next.ServeHTTP(w, r.WithContext(ctx))

			ws, ok := w.(interface {
				Status() int
			})
			if ok {
				f["status"] = ws.Status()
			}

			ln.Log(ctx, f)
		})
	}
}
