package firewall

import (
	"net/http"

	"ems.agt/features/firewall/model"
	"ems.agt/features/firewall/service"
	"ems.agt/lib/core/utils/ctx"
	"ems.agt/lib/core/vo/result"
	"ems.agt/lib/services"
	"ems.agt/restagent/config"
)

// 防火墙管理接口添加到路由
func Routers() []services.RouterItem {
	// 实例化控制层 FirewallApi 结构体
	var apis = &FirewallApi{
		firewallService: *service.NewServiceFirewall,
	}

	rs := [...]services.RouterItem{
		{
			Method:     "GET",
			Pattern:    "/base",
			Handler:    apis.BaseInfo,
			Middleware: nil, //midware.Authorize(nil),
		},
		{
			Method:     "POST",
			Pattern:    "/rule",
			Handler:    apis.Rule,
			Middleware: nil, //midware.Authorize(nil),
		},
		// 添加更多的 Router 对象...
	}

	// 生成两组前缀路由
	rsPrefix := []services.RouterItem{}
	for _, v := range rs {
		path := "/firewallManage/{apiVersion}" + v.Pattern
		// 固定前缀
		v.Pattern = config.DefaultUriPrefix + path
		rsPrefix = append(rsPrefix, v)
		// 可配置
		v.Pattern = config.UriPrefix + path
		rsPrefix = append(rsPrefix, v)
	}
	return rsPrefix
}

// 防火墙管理
//
// PATH /firewallManage
type FirewallApi struct {
	firewallService service.ServiceFirewall
}

// 获取防火墙基础信息
//
// GET /base
func (s *FirewallApi) BaseInfo(w http.ResponseWriter, r *http.Request) {
	data, err := s.firewallService.LoadBaseInfo()
	if err != nil {
		ctx.JSON(w, 200, result.ErrMsg(err.Error()))
		return
	}

	ctx.JSON(w, 200, result.OkData(data))
}

// 获取防火墙规则列表分页
//
// GET /rule
func (s *FirewallApi) Rule(w http.ResponseWriter, r *http.Request) {
	var body model.RuleQuerys
	err := ctx.ShouldBindJSON(r, &body)
	if err != nil || body.Type == "" {
		ctx.JSON(w, 400, result.CodeMsg(400, "parameter error"))
		return
	}
	data, err := s.firewallService.RulePage(body)
	if err != nil {
		ctx.JSON(w, 400, result.ErrMsg(err.Error()))
		return
	}

	ctx.JSON(w, 200, result.OkData(data))
}
