package pkg

import (
	"log"
	"net/http"
	"os"
	"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 {
	stdout := log.New(os.Stdout, "", log.LstdFlags)
	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
		}
		stdout.Printf("HTTP - %s %s \"%s\" %d %d %s\n",
			remoteAddr(r),
			r.Method,
			r.URL.Path,
			statusCode,
			logger.responseSize,
			time.Since(t),
		)

	})
}
