package auxgin

import (
	"bytes"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func LogMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		start := time.Now()

		ctx.Next()

		var reqSize int64
		var method string
		var reqURI string
		if ctx.Request != nil {
			reqSize = ctx.Request.ContentLength
			method = ctx.Request.Method
			reqURI = ctx.Request.RequestURI
		}

		duration := time.Since(start).Microseconds()
		remAddr := ctx.RemoteIP()

		var resCode int
		var resSize int
		if ctx.Writer != nil {
			resCode = ctx.Writer.Status()
			resSize = ctx.Writer.Size()
		}

		logString := fmt.Sprintf("%s %s %s in=%d out=%d res=%d %dms",
			remAddr, method, reqURI, reqSize, resSize, resCode, duration)

		logger := logrus.WithField("object", "accesslog")
		logger.Infoln(logString)
	}
}

type LogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (lw LogWriter) Write(data []byte) (int, error) {
	lw.body.Write(data)
	return lw.ResponseWriter.Write(data)
}

func (lw LogWriter) WriteString(data string) (int, error) {
	lw.body.WriteString(data)
	return lw.ResponseWriter.WriteString(data)
}
