package setup

// |@@| C

import (
	"context"
	"gardening/src/app/routers"
	"gardening/src/lib/logger"
	"gardening/src/lib/middlewares"
	"gardening/src/lib/operating_system"
	"github.com/gin-gonic/gin"
	"strings"
)

type GinRouter struct {
	AjxRouter                *routers.AjxRouter
	ApiRouter                *routers.ApiRouter
	AppRouter                *routers.AppRouter
	AuthRouter               *routers.AuthRouter
	DevtMiddleware           *middlewares.DevtMiddleware
	ExchangeRouter           *routers.ExchangeRouter
	Logger                   *logger.Logger
	MiscRouter               *routers.MiscRouter
	OperatingSystemInterface operating_system.OperatingSystemInterface
	RecoveryMiddleware       *middlewares.RecoveryMiddleware
	SessionMiddleware        *middlewares.SessionMiddleware
	UidMiddleware            *middlewares.UidMiddleware
}

func (this *GinRouter) Setup(ctx context.Context) *gin.Engine {
	env := this.OperatingSystemInterface.Getenv(ctx, "ENV")
	if env == "prod" {
		gin.SetMode(gin.ReleaseMode)
	}
	if env == "test" {
		gin.SetMode(gin.TestMode)
	}
	if env == "dev" {
		gin.SetMode(gin.DebugMode)
	}

	if env == "dev" || env == "test" {
		gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {}
	}

	r := gin.New()

	r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
		Output: this,
	}))
	r.Use(gin.Recovery())

	r.Use(this.UidMiddleware.Act())
	r.Use(this.RecoveryMiddleware.Act())
	r.Use(this.SessionMiddleware.Act())
	if env == "dev" {
		r.Use(this.DevtMiddleware.Act())
	}

	this.MiscRouter.Act(ctx, r)
	this.AuthRouter.Act(ctx, r)
	this.AppRouter.Act(ctx, r)
	this.AjxRouter.Act(ctx, r)
	this.ApiRouter.Act(ctx, r)
	this.ExchangeRouter.Act(ctx, r)

	return r
}
func (this *GinRouter) Write(p []byte) (n int, err error) {
	env := this.OperatingSystemInterface.Getenv(context.Background(), "ENV")

	s := string(p)
	s = strings.TrimSuffix(s, "\n")
	if env == "dev" {
		this.Logger.Info(context.Background(), s)
	} else {
		this.Logger.Debug(context.Background(), s)
	}
	return len(p), nil
}
