package middlewares

// |@@| C

import (
	"gardening/src/lib/dev_tool"
	"gardening/src/lib/logger"
	"github.com/gin-gonic/gin"
)

type DevtMiddleware struct {
	DevTool *dev_tool.DevTool
	Logger  *logger.Logger
}

func (this *DevtMiddleware) Act() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()

		if c.FullPath() == "/exchange/new-report" {
			return
		}
		record := this.DevTool.GetCurrentRecord(c)
		this.fillParams(c, record)

		err := this.DevTool.SendRecord(c)
		if err != nil {
			this.Logger.Warn(c, "Cannot send log report to devt")
		}
	}
}

func (this *DevtMiddleware) fillParams(c *gin.Context, record *dev_tool.Record) {
	record.RouteInfo.Params = make(map[string]string)

	// Capture route parameters
	for _, param := range c.Params {
		record.RouteInfo.Params[param.Key] = param.Value
	}

	// Capture query parameters
	for key, values := range c.Request.URL.Query() {
		if len(values) > 0 {
			record.RouteInfo.Params[key] = values[0]
		}
	}

	// Capture form (POST) parameters
	c.Request.ParseForm()
	for key, values := range c.Request.PostForm {
		if len(values) > 0 {
			record.RouteInfo.Params[key] = values[0]
		}
	}

	// Capture Parent Uid
	record.ParentUid = c.GetHeader("devt_parent_uid")
}
