package middleware

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

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

// Trace adds go stdlib tracing to this http handler.
func Trace(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sp := trace.New(filepath.Base(os.Args[0]+"-https"), 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{
			"method":      r.Method,
			"path":        r.URL.Path,
			"remote_addr": r.RemoteAddr,
			"user_agent":  r.UserAgent(),
		}

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

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

		ln.Log(ctx, f)
	})
}
