package ginext

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type GinWrapper struct {
	engine          *gin.Engine
	SuppressGinLogs bool

	allowCors      bool
	ginDebug       bool
	requestTimeout time.Duration
}

func NewEngine(allowCors bool, ginDebug bool, timeout time.Duration) *GinWrapper {
	engine := gin.New()

	wrapper := &GinWrapper{
		engine:          engine,
		SuppressGinLogs: false,
		allowCors:       allowCors,
		ginDebug:        ginDebug,
		requestTimeout:  timeout,
	}

	engine.RedirectFixedPath = false
	engine.RedirectTrailingSlash = false

	if allowCors {
		engine.Use(CorsMiddleware())
	}

	if ginDebug {
		ginlogger := gin.Logger()
		engine.Use(func(context *gin.Context) {
			if !wrapper.SuppressGinLogs {
				ginlogger(context)
			}
		})
	}

	return wrapper
}

func (w *GinWrapper) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	w.engine.ServeHTTP(writer, request)
}