package pkg

import (
	"log"
	"net/http"
	"time"
)

type loggerResponseWriter struct {
	http.ResponseWriter
	statusCode   int
	responseSize int
}

func (w *loggerResponseWriter) WriteHeader(statusCode int) {
	w.statusCode = statusCode
	w.ResponseWriter.WriteHeader(statusCode)
}

func (w *loggerResponseWriter) Write(b []byte) (int, error) {
	w.responseSize += len(b)
	return w.ResponseWriter.Write(b)
}

func (w *loggerResponseWriter) Flush() {
	if f, ok := w.ResponseWriter.(http.Flusher); ok {
		f.Flush()
	}
}

func Logger(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		t := time.Now()
		logger := loggerResponseWriter{w, 0, 0}

		handler.ServeHTTP(&logger, r)

		statusCode := logger.statusCode
		if statusCode == 0 {
			statusCode = http.StatusOK
		}
		referer := r.Referer()
		if referer == "" {
			referer = "-"
		}
		log.Printf("HTTP - %s - - [%s] \"%s %s %s\" %d %d \"%s\" \"%s\" %s\n",
			r.RemoteAddr,
			t.Format("02/Jan/2006:15:04:05 -0700"),
			r.Method,
			r.URL.Path,
			r.Proto,
			statusCode,
			logger.responseSize,
			referer,
			r.UserAgent(),
			time.Since(t),
		)

	})
}
