package middleware

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"time"
)

func CreateRequstLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
	return func(ctx *context.Context) {
		requestId := fmt.Sprintf("%v.%v.%v ", ctx.Input.Method(), ctx.Input.URI(), time.Now().UnixNano())
		ctx.Request.Header.Add("requestId", requestId)
		var body string = "{}"
		if ctx.Input.GetData("requestBody") != nil {
			body = string(ctx.Input.GetData("requestBody").([]byte))
		}
		logger.Debug(fmt.Sprintf("====>Recv RequestId:%s BodyData:%s \n Header:%v", requestId, body, ctx.Request.Header))
	}
}

func CreateResponseLogFilter(logger *logs.BeeLogger) func(ctx *context.Context) {
	return func(ctx *context.Context) {
		requestId := ctx.Request.Header.Get("requestId")
		body, _ := json.Marshal(ctx.Input.GetData("outputData"))
		if len(body) > 1000 {
			body = body[:1000]
		}
		logger.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
	}
}

func CreateRequestBodyFilter() func(ctx *context.Context) {
	return func(ctx *context.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.Input.SetData("requestBody", body)
			ctx.Request.Body.Close()
		}
		//if len(ctx.Input.RequestBody) == 0 {
		//
		//} else {
		//	ctx.Input.SetData("requestBody", ctx.Input.RequestBody)
		//}
	}
}