package api

import (
	"context"
	"copter-train/conf"
	"copter-train/db"
	"copter-train/db/repo"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
)

type Service struct {
	Gin   *gin.Engine
	Mongo *db.MongoDB
	Redis *redis.Client
	Port  int32
	JWT   *UtilsJwt
	Conf  *conf.AppConf
}

var ApiService *Service

func (svc *Service) Run() {
	svc.Gin.Run(fmt.Sprintf(":%d", svc.Port))
}

type ApiSession struct {
	Svc  *Service
	User *JWTUser
}

func (api *ApiSession) CreateRepoCtx() *repo.RepoSession {
	return &repo.RepoSession{
		Ctx:    context.Background(),
		Client: api.Svc.Mongo,
	}
}

// GinRouter 路由
type GinRouter struct {
	group *gin.RouterGroup
	svc   *Service
}

func (svc *Service) NewGinRouter(path string) *GinRouter {
	return &GinRouter{group: svc.Gin.Group(path), svc: svc}
}

// RouterInterface 路由接口
type RouterInterface interface {
	GET(path string, httpHandler Handler)
	POST(path string, httpHandler Handler)
}

// GET http Get 请求
func (g GinRouter) GET(path string, httpHandler Handler) {
	g.group.GET(path, ResultWrapper(httpHandler, g.svc))
}

// POST http POST 请求
func (g GinRouter) POST(path string, httpHandler Handler) {
	g.group.POST(path, ResultWrapper(httpHandler, g.svc))
}

// GETJWT http Get 请求
func (g GinRouter) GETJWT(path string, httpHandler JWTHander) {
	g.group.GET(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
}

// POSTJWT http POST 请求
func (g GinRouter) POSTJWT(path string, httpHandler JWTHander) {
	g.group.POST(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
}

// DeleteJWT http POST 请求
func (g GinRouter) DeleteJWT(path string, httpHandler JWTHander) {
	g.group.DELETE(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
}

// 代参数判断权限
func (g GinRouter) GETJWTKEY(path string, httpHandler JWTHander, keys ...string) {
	g.group.GET(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapperKey(httpHandler, g.svc, keys))
}

func (g GinRouter) POSTJWTKEY(path string, httpHandler JWTHander, keys ...string) {
	g.group.POST(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapperKey(httpHandler, g.svc, keys))
}
