package middleware

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
	"io/ioutil"
	"net/http"
	"time"
)

func CreateRequstLogFilter() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		requestId := fmt.Sprintf("%v.%v", ctx.Request.Method, ctx.Request.RequestURI)
		ctx.Set("requestId", requestId)
		var body string = "{}"
		if _, ok := ctx.Get("requestBody"); ok {
			data, _ := ctx.Get("requestBody")
			body = string(data.([]byte))
		}
		start := time.Now()
		ctx.Next()
		end := time.Now()
		latency := end.Sub(start)

		v, _ := ctx.Get("outputData")
		rspBody, _ := json.Marshal(v)
		if len(rspBody) > 500 {
			rspBody = rspBody[:500]
		}
		log.Debug(fmt.Sprintf("====>Recv User:%v | %v | %s | %v | \nAuth=%v \nReqBody:%s \nRspBody:%v", ctx.Query("UserId"), ctx.ClientIP(), requestId, latency, ctx.Query("x-mmm-accesstoken"), body, string(rspBody)))
	}
}

func CreateResponseLogFilter() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		requestId, _ := ctx.Get("requestId")
		v, _ := ctx.Get("outputData")
		body, _ := json.Marshal(v)
		if len(body) > 1000 {
			body = body[:1000]
		}
		log.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
	}
}

func CreateRequestBodyFilter() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		if ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut {
			body, _ := ioutil.ReadAll(ctx.Request.Body)
			if len(body) == 0 {
				body = []byte("{}")
			}
			ctx.Set("requestBody", body)
			ctx.Request.Body.Close()
		}
	}
}