package main

import (
	"sparrow/pkg/generator"
	"sparrow/services/knowoapi/controllers"
	"sparrow/services/knowoapi/model"
	"sparrow/services/knowoapi/services"

	"github.com/opentracing/opentracing-go"

	jwt "github.com/dgrijalva/jwt-go"
	jwtmiddleware "github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
)

func registerErrors(srv *iris.Application) {
	srv.OnAnyErrorCode(handleErrors)
}
func handleErrors(ctx iris.Context) {
	//logger.Default().Serve(ctx)
	err := controllers.ErrorResponse{
		Code:    ctx.GetStatusCode(),
		Message: ctx.Values().GetStringDefault("reason", "未知错误"),
	}
	ctx.JSON(err)
}

// jwt 中间件配置
func newJWThandle() func(ctx iris.Context) {
	jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(model.SignedString), nil
		},
		ErrorHandler: func(ctx iris.Context, message string) {
			ctx.StatusCode(iris.StatusUnauthorized)
			ctx.Values().Set("reason", message)
		},
		SigningMethod: jwt.SigningMethodHS256,
	})

	return jwtHandler.Serve
}

// 请求路由
func registerRouters(srv *iris.Application, models *model.All, gen *generator.KeyGenerator) {
	pService := services.NewProductService(models, gen)
	userService := services.NewUserService(models, gen)
	appService := services.NewAppService(models, gen)
	sensorService := services.NewSensorService(models)
	protocalService := services.NewProtocalService(models)
	alertService := services.NewAlertService(models)
	deviceService := services.NewDeviceService(models)
	roleService := services.NewRoleService(models)
	ruleChainService := services.NewRuleChainService(models)
	subDeviceService := services.NewSubDeviceService(models)
	v1router := srv.Party("/api/v1", func(ctx iris.Context) {
		span := opentracing.StartSpan(ctx.Path())
		defer span.Finish()
		span.SetTag("http.method", ctx.Method())
		span.SetTag("http.url", ctx.Path())
		span.SetTag("http.status_code", ctx.GetStatusCode())
		ctx.Values().Set("span", span)
		ctx.Next()
	})

	// 登陆，注册
	loginAPI := mvc.New(v1router.Party("/"))
	loginAPI.Register(userService).Handle(new(controllers.UserController))

	// 用户接口组
	userRouter := v1router.Party("/user", newJWThandle())

	// user api
	userAPI := mvc.New(userRouter.Party("/"))
	userAPI.Register(userService).Handle(new(controllers.UserController))
	// product api
	productAPI := mvc.New(userRouter.Party("/product"))
	productAPI.Register(pService).Handle(new(controllers.ProductController))
	//application api
	appAPI := mvc.New(userRouter.Party("/application"))
	appAPI.Register(appService).Handle(new(controllers.AppController))
	// sensor api
	sensorAPI := mvc.New(userRouter.Party("/sensor"))
	sensorAPI.Register(sensorService).Handle(new(controllers.SensorController))
	// protocal api
	protocalAPI := mvc.New(userRouter.Party("/protocal"))
	protocalAPI.Register(protocalService).Handle(new(controllers.ProtocalController))
	//alert api
	alertAPI := mvc.New(userRouter.Party("/alert"))
	alertAPI.Register(alertService).Handle(new(controllers.AlertController))
	//device api
	deviceAPI := mvc.New(userRouter.Party("/device"))
	deviceAPI.Register(deviceService).Handle(new(controllers.DeviceController))

	//管理员接口组
	adminRouter := v1router.Party("/admin", newJWThandle())
	RoleAPI := mvc.New(adminRouter.Party("/role"))
	RoleAPI.Register(roleService).Handle(new(controllers.RoleController))

	// ruleChain api
	RuleChainAPI := mvc.New(userRouter.Party("/rule_chain"))
	RuleChainAPI.Register(ruleChainService).Handle(new(controllers.RuleChainController))

	// subDevice api
	subDeviceAPI := mvc.New(userRouter).Party("/sub_device")
	subDeviceAPI.Register(subDeviceService).Handle(new(controllers.SubDeviceController))
}
