package router

import (
	middlewares "bpmsapi/middleware"
	"bpmsapi/util"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
)

func InitRouters() (*gin.Engine, *os.File) {

	gin.DisableConsoleColor()
	dt := time.Now()
	var filename string
	//environment := util.GetEnvironment()
	//fmt.Println(util.)
	if strings.ToLower(util.Environment) == "production" || strings.ToLower(util.Environment) == "test" {
		filename = fmt.Sprintf("%s%s%s", "/var/www/bpms_api_backend/bpms_apilog_", dt.Format("01022006"), ".log")
	} else if strings.ToLower(util.Environment) == "local" {
		filename = fmt.Sprintf("%s%s%s", "bpmslog_", dt.Format("01022006"), ".log")
	}
	fmt.Println(filename)
	f, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	gin.DefaultWriter = io.MultiWriter(f)
	log.SetOutput(f)
	router := gin.New()
	router.Use(gin.Recovery())
	router.Use(middlewares.CORSMiddleware())
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		en := en.New()
		uni := ut.New(en, en)
		util.Trans, _ = uni.GetTranslator("en")
		enTranslations.RegisterDefaultTranslations(v, util.Trans)
	}
	router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))
	router.Use(gin.Recovery())
	bpms := router.Group("/bpms")
	bpms.Use(middlewares.ResultMiddleware())
	InitCommonRouter(bpms)

	bpmsSecured := router.Group("/bpmssecured")
	bpmsSecured.Use(middlewares.JWTAuthMiddleware())
	InitUserRouter(bpmsSecured)
	InitAdminRouter(bpmsSecured)
	InitSuperAdminRouter(bpmsSecured)
	InitTechnicianRouter(bpmsSecured)

	log.Println("BPMS: MainRouters: InitRouters: Intialize router working")
	/*api := router.Group("/common")
	{
		api.Use(middlewares.ResultMiddleware())
		common.RegisterRouter(api)
	}
	scrd := router.Group("/secured")
	{
		scrd.Use(middlewares.JWTAuthMiddleware())
		secured.RegisterAdminRouter(scrd)
		secured.RegisterUserRouter(scrd)
	}*/

	return router, f

}
